@xmanrui/dsh-im 5.0.3 → 5.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.
Files changed (39) hide show
  1. package/README.en.md +8 -0
  2. package/README.md +8 -0
  3. package/lib/client.js +654 -495
  4. package/lib/index.js +318 -294
  5. package/package.json +1 -1
  6. package/plugin-src/client/channels/feishu/group-settings.js +10 -9
  7. package/plugin-src/client/channels/feishu/index.js +3 -3
  8. package/plugin-src/client/global-settings.js +29 -24
  9. package/plugin-src/client/group-history-settings.js +72 -0
  10. package/plugin-src/client/i18n.js +19 -3
  11. package/plugin-src/client/styles.js +12 -4
  12. package/plugin-src/host/channels/feishu/production.mjs +2 -0
  13. package/plugin-src/host/channels/feishu/rpc.mjs +5 -4
  14. package/plugin-src/host/channels/qq/production.mjs +2 -0
  15. package/plugin-src/host/channels/shared/production.mjs +2 -0
  16. package/plugin-src/host/channels/slack/production.mjs +2 -0
  17. package/plugin-src/host/channels/whatsapp/production.mjs +2 -0
  18. package/plugin-src/host/group-history-rpc.mjs +22 -0
  19. package/plugin-src/host/group-history-runtime.mjs +21 -0
  20. package/plugin-src/host/inbound-ttl-rpc.mjs +6 -2
  21. package/plugin-src/host/index.mjs +4 -1
  22. package/src/channels/discord/discord-runtime.mjs +8 -0
  23. package/src/channels/feishu/bridge.mjs +23 -1
  24. package/src/channels/feishu/feishu-runtime.mjs +5 -0
  25. package/src/channels/feishu/multi-bot-controller.mjs +17 -3
  26. package/src/channels/feishu/plugin-controller.mjs +2 -0
  27. package/src/channels/feishu/repair-manager.mjs +2 -1
  28. package/src/channels/qq/qq-bridge.mjs +19 -0
  29. package/src/channels/qq/qq-runtime.mjs +4 -0
  30. package/src/channels/shared/group-history-access.mjs +133 -0
  31. package/src/channels/shared/group-history-store.mjs +383 -0
  32. package/src/channels/shared/group-history.mjs +56 -0
  33. package/src/channels/shared/harness-client.mjs +3 -0
  34. package/src/channels/shared/i18n-en/feishu.mjs +2 -2
  35. package/src/channels/shared/text-harness-bridge.mjs +1 -0
  36. package/src/channels/slack/manifest.mjs +2 -0
  37. package/src/channels/slack/slack-runtime.mjs +10 -2
  38. package/src/channels/telegram/telegram-runtime.mjs +7 -0
  39. package/src/channels/whatsapp/whatsapp-runtime.mjs +20 -0
@@ -0,0 +1,383 @@
1
+ import { DatabaseSync } from 'node:sqlite';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { createReadStream } from 'node:fs';
4
+ import { chmod, mkdir, open, readFile, readdir, rename, rm, writeFile } from 'node:fs/promises';
5
+ import { dirname, join, resolve } from 'node:path';
6
+ import { stageInboundFiles } from './inbound-file.mjs';
7
+
8
+ export const GROUP_HISTORY_CHANNELS = Object.freeze(['whatsapp', 'feishu', 'telegram', 'discord', 'slack', 'qq']);
9
+ export const DEFAULT_GROUP_HISTORY_DAYS = 14;
10
+ const DAY = 86_400_000;
11
+ const MAX_FILE_BYTES = 100 * 1024 * 1024;
12
+
13
+ function untilAbort(promise, signal) {
14
+ signal.throwIfAborted();
15
+ return new Promise((resolve, reject) => {
16
+ const abort = () => reject(signal.reason);
17
+ signal.addEventListener('abort', abort, { once: true });
18
+ Promise.resolve(promise).then(resolve, reject).finally(() => signal.removeEventListener('abort', abort));
19
+ });
20
+ }
21
+
22
+ export function normalizeGroupHistoryDays(value) {
23
+ if (typeof value !== 'number' && typeof value !== 'string') return null;
24
+ if (typeof value === 'string' && !/^\d+$/.test(value.trim())) return null;
25
+ const days = Number(value);
26
+ return Number.isSafeInteger(days) && days > 0 && Number.isSafeInteger(days * DAY) ? days : null;
27
+ }
28
+
29
+ function invalid(message) { return Object.assign(new Error(message), { code: 'group-history-invalid' }); }
30
+ function text(value, max = 512) { return typeof value === 'string' ? value.slice(0, max) : ''; }
31
+ function timestamp(value, fallback) {
32
+ const parsed = typeof value === 'string' ? Date.parse(value) : Number(value);
33
+ return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : fallback;
34
+ }
35
+ function attachmentView(row) {
36
+ return { id: row.id, messageId: row.message_id, name: row.name, mimeType: row.mime_type,
37
+ sizeBytes: row.size_bytes, status: row.status, error: row.last_error || null };
38
+ }
39
+
40
+ /** A single group-owned archive. Bot credentials and AI session ownership never enter this database. */
41
+ export class GroupHistoryStore {
42
+ #root;
43
+ #db;
44
+ #ready;
45
+ #days = DEFAULT_GROUP_HISTORY_DAYS;
46
+ #settingsError = null;
47
+ #maintenance = Promise.resolve();
48
+ #now;
49
+ #logger;
50
+ #timer;
51
+ #closing = false;
52
+ #jobs = new Map();
53
+ #active = new Map();
54
+ #idle = [];
55
+ #sweep;
56
+ #maxFileBytes;
57
+ #downloadTimeoutMs;
58
+ #copyService;
59
+ #close;
60
+
61
+ constructor(root, { now = Date.now, logger = console, maxFileBytes = MAX_FILE_BYTES, downloadTimeoutMs = 60_000, copyService } = {}) {
62
+ this.#root = resolve(root);
63
+ this.#now = now;
64
+ this.#logger = logger;
65
+ this.#maxFileBytes = maxFileBytes;
66
+ this.#downloadTimeoutMs = downloadTimeoutMs;
67
+ this.#copyService = copyService;
68
+ }
69
+
70
+ get root() { return this.#root; }
71
+ ready() { return this.#ready ??= this.#load(); }
72
+ cutoff() { return this.#now() - this.#days * DAY; }
73
+
74
+ async #load() {
75
+ await mkdir(join(this.#root, 'group-files'), { recursive: true, mode: 0o700 });
76
+ try {
77
+ const data = JSON.parse(await readFile(join(this.#root, 'general-settings.json'), 'utf8'));
78
+ const days = normalizeGroupHistoryDays(data.groupHistoryRetentionDays);
79
+ if (data.version !== 1 || days === null) throw invalid('群记录设置损坏,请重新保存保留天数。');
80
+ this.#days = days;
81
+ } catch (error) {
82
+ if (error.code !== 'ENOENT') this.#settingsError = '群记录设置无法读取,已暂停自动清理,请重新保存保留天数。';
83
+ }
84
+ const path = join(this.#root, 'group-history.sqlite');
85
+ this.#db = new DatabaseSync(path);
86
+ await chmod(path, 0o600);
87
+ this.#db.exec(`PRAGMA foreign_keys = ON; PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 3000;
88
+ CREATE TABLE IF NOT EXISTS groups (
89
+ id TEXT PRIMARY KEY, channel TEXT NOT NULL, platform_scope TEXT NOT NULL DEFAULT '',
90
+ platform_group_id TEXT NOT NULL, name TEXT NOT NULL DEFAULT '',
91
+ recording_started_at INTEGER, last_received_at INTEGER, capability TEXT NOT NULL DEFAULT '',
92
+ UNIQUE(channel, platform_scope, platform_group_id));
93
+ CREATE TABLE IF NOT EXISTS messages (
94
+ id TEXT PRIMARY KEY, group_id TEXT NOT NULL REFERENCES groups(id), platform_message_id TEXT NOT NULL,
95
+ sender_id TEXT NOT NULL, sender_name TEXT NOT NULL DEFAULT '', sent_at INTEGER NOT NULL,
96
+ received_at INTEGER NOT NULL, type TEXT NOT NULL, text TEXT NOT NULL,
97
+ thread_id TEXT, reply_to_message_id TEXT, UNIQUE(group_id, platform_message_id));
98
+ CREATE INDEX IF NOT EXISTS messages_group_time ON messages(group_id, sent_at, id);
99
+ CREATE INDEX IF NOT EXISTS messages_expiry ON messages(sent_at);
100
+ CREATE TABLE IF NOT EXISTS attachments (
101
+ id TEXT PRIMARY KEY, message_id TEXT NOT NULL REFERENCES messages(id) ON DELETE CASCADE,
102
+ source_attachment_key TEXT NOT NULL, name TEXT NOT NULL, mime_type TEXT NOT NULL,
103
+ size_bytes INTEGER, relative_path TEXT, status TEXT NOT NULL, last_error TEXT NOT NULL DEFAULT '',
104
+ UNIQUE(message_id, source_attachment_key));`);
105
+ this.#db.prepare("UPDATE attachments SET status = 'unavailable', last_error = ? WHERE status = 'pending'")
106
+ .run('下载被重启中断,原文件尚未保存。');
107
+ // Only our fixed-depth partial files are removed; ready files remain untouched.
108
+ for (const group of await readdir(join(this.#root, 'group-files'), { withFileTypes: true })) {
109
+ if (!group.isDirectory()) continue;
110
+ const groupPath = join(this.#root, 'group-files', group.name);
111
+ for (const message of await readdir(groupPath, { withFileTypes: true })) {
112
+ if (!message.isDirectory()) continue;
113
+ const messagePath = join(groupPath, message.name);
114
+ for (const file of await readdir(messagePath, { withFileTypes: true })) {
115
+ if (file.isFile() && file.name.endsWith('.part')) await rm(join(messagePath, file.name), { force: true });
116
+ }
117
+ }
118
+ }
119
+ return this;
120
+ }
121
+
122
+ async start() {
123
+ await this.ready();
124
+ if (this.#timer || this.#closing) return;
125
+ await this.sweep();
126
+ if (this.#closing) return;
127
+ this.#timer = setInterval(() => void this.sweep().catch((error) => this.#warn(error)), 3_600_000);
128
+ this.#timer.unref?.();
129
+ }
130
+
131
+ #warn(error) { this.#logger.warn?.('[dsh-im] group history:', error?.message ?? 'operation failed'); }
132
+
133
+ async settings() {
134
+ await this.ready();
135
+ return { groupHistoryRetentionDays: this.#days, ...(this.#settingsError ? { error: this.#settingsError } : {}) };
136
+ }
137
+
138
+ setRetentionDays(value) {
139
+ const days = normalizeGroupHistoryDays(value);
140
+ if (days === null) return Promise.reject(invalid('保留天数必须为正整数。'));
141
+ const write = this.#maintenance.catch(() => {}).then(async () => {
142
+ await this.ready();
143
+ const path = join(this.#root, 'general-settings.json');
144
+ const temporary = `${path}.${randomUUID()}.tmp`;
145
+ try {
146
+ await writeFile(temporary, `${JSON.stringify({ version: 1, groupHistoryRetentionDays: days }, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
147
+ await rename(temporary, path);
148
+ } finally { await rm(temporary, { force: true }); }
149
+ this.#days = days;
150
+ this.#settingsError = null;
151
+ void this.sweep().catch((error) => this.#warn(error));
152
+ return this.settings();
153
+ });
154
+ this.#maintenance = write;
155
+ return write;
156
+ }
157
+
158
+ async capture(entry) {
159
+ await this.ready();
160
+ if (this.#closing || !entry || !GROUP_HISTORY_CHANNELS.includes(entry.channel)) return null;
161
+ const platformGroupId = text(entry.groupId);
162
+ if (!platformGroupId) return null;
163
+ const scope = text(entry.scope);
164
+ let group = this.#db.prepare('SELECT * FROM groups WHERE channel = ? AND platform_scope = ? AND platform_group_id = ?')
165
+ .get(entry.channel, scope, platformGroupId);
166
+ if (!group) {
167
+ const id = randomUUID();
168
+ this.#db.prepare('INSERT INTO groups(id, channel, platform_scope, platform_group_id, name, capability) VALUES(?,?,?,?,?,?)')
169
+ .run(id, entry.channel, scope, platformGroupId, text(entry.groupName), text(entry.capability, 1000));
170
+ group = this.#db.prepare('SELECT * FROM groups WHERE id = ?').get(id);
171
+ } else if (entry.groupName || entry.capability) {
172
+ this.#db.prepare('UPDATE groups SET name = ?, capability = ? WHERE id = ?')
173
+ .run(text(entry.groupName) || group.name, text(entry.capability, 1000) || group.capability, group.id);
174
+ }
175
+ const context = Object.freeze({ store: this, groupId: group.id });
176
+ // Older databases may retain an enabled column. It no longer gates
177
+ // recording: every group delivered by the platform is recorded by default.
178
+ if (this.#settingsError) return context;
179
+ const messageId = text(entry.messageId, 2048);
180
+ if (!messageId || !entry.senderId) return context;
181
+ const now = this.#now();
182
+ const sentAt = timestamp(entry.sentAt, now);
183
+ if (sentAt < this.cutoff()) return context;
184
+ this.#db.exec('BEGIN');
185
+ const queued = [];
186
+ try {
187
+ this.#db.prepare(`INSERT INTO messages(id,group_id,platform_message_id,sender_id,sender_name,sent_at,received_at,type,text,thread_id,reply_to_message_id)
188
+ VALUES(?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(group_id,platform_message_id) DO NOTHING`)
189
+ .run(randomUUID(), group.id, messageId, text(entry.senderId), text(entry.senderName), sentAt, now,
190
+ text(entry.type) || 'text', typeof entry.text === 'string' ? entry.text : '', text(entry.threadId) || null, text(entry.replyToMessageId, 2048) || null);
191
+ const message = this.#db.prepare('SELECT id FROM messages WHERE group_id = ? AND platform_message_id = ?').get(group.id, messageId);
192
+ // Repeated delivery may carry metadata missing from the first event.
193
+ for (const [index, source] of (entry.attachments ?? []).entries()) {
194
+ const key = text(source.key) || String(index);
195
+ const size = Number.isSafeInteger(source.size) && source.size >= 0 ? source.size : null;
196
+ this.#db.prepare(`INSERT INTO attachments(id,message_id,source_attachment_key,name,mime_type,size_bytes,status)
197
+ VALUES(?,?,?,?,?,?,?) ON CONFLICT(message_id,source_attachment_key) DO NOTHING`)
198
+ .run(randomUUID(), message.id, key, text(source.name) || `file-${index + 1}`, text(source.mediaType) || 'application/octet-stream', size, 'pending');
199
+ const attachment = this.#db.prepare('SELECT * FROM attachments WHERE message_id = ? AND source_attachment_key = ?').get(message.id, key);
200
+ if (attachment.status !== 'ready' && !this.#jobs.has(attachment.id) && !this.#active.has(attachment.id)) {
201
+ queued.push({ attachment, source, groupId: group.id, messageId: message.id });
202
+ }
203
+ }
204
+ this.#db.prepare('UPDATE groups SET last_received_at = ?, recording_started_at = coalesce(recording_started_at, ?) WHERE id = ?')
205
+ .run(now, now, group.id);
206
+ this.#db.exec('COMMIT');
207
+ } catch (error) { this.#db.exec('ROLLBACK'); throw error; }
208
+ for (const job of queued) this.#jobs.set(job.attachment.id, job);
209
+ this.#pump();
210
+ return context;
211
+ }
212
+
213
+ #pump() {
214
+ while (this.#active.size < 2 && this.#jobs.size) {
215
+ const [id, job] = this.#jobs.entries().next().value;
216
+ this.#jobs.delete(id);
217
+ const task = this.#download(job).catch((error) => this.#warn(error)).finally(() => {
218
+ this.#active.delete(id);
219
+ this.#pump();
220
+ });
221
+ this.#active.set(id, task);
222
+ }
223
+ if (!this.#active.size && !this.#jobs.size) for (const done of this.#idle.splice(0)) done();
224
+ }
225
+
226
+ async #download({ attachment, source, groupId, messageId }) {
227
+ const relativePath = join('group-files', groupId, messageId, attachment.id);
228
+ const path = join(this.#root, relativePath);
229
+ const temporary = `${path}.part`;
230
+ let handle;
231
+ let iterator;
232
+ try {
233
+ if (typeof source.load !== 'function') throw invalid('平台没有提供可下载的文件。');
234
+ if (attachment.size_bytes > this.#maxFileBytes) throw invalid('文件超过群文件保存大小上限。');
235
+ this.#db.prepare("UPDATE attachments SET status = 'pending', last_error = '' WHERE id = ?").run(attachment.id);
236
+ const signal = AbortSignal.timeout(this.#downloadTimeoutMs);
237
+ const loaded = await untilAbort(source.load({ signal, maxBytes: this.#maxFileBytes }), signal);
238
+ const value = Buffer.isBuffer(loaded) || loaded instanceof Uint8Array
239
+ ? loaded : loaded?.stream ?? loaded?.data ?? loaded?.buffer ?? loaded;
240
+ const stream = Buffer.isBuffer(value) || value instanceof Uint8Array ? [value] : value;
241
+ if (!stream || !(Symbol.asyncIterator in Object(stream) || Symbol.iterator in Object(stream))) throw invalid('文件下载未返回内容。');
242
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
243
+ handle = await open(temporary, 'w', 0o600);
244
+ let size = 0;
245
+ iterator = stream[Symbol.asyncIterator]?.() ?? stream[Symbol.iterator]();
246
+ while (true) {
247
+ const { value: chunk, done } = await untilAbort(iterator.next(), signal);
248
+ if (done) break;
249
+ signal.throwIfAborted();
250
+ const bytes = Buffer.from(chunk);
251
+ size += bytes.length;
252
+ if (size > this.#maxFileBytes) throw invalid('文件超过群文件保存大小上限。');
253
+ await handle.writeFile(bytes);
254
+ }
255
+ await handle.close(); handle = null;
256
+ const message = this.#db.prepare('SELECT sent_at FROM messages WHERE id = ?').get(messageId);
257
+ if (!message || message.sent_at < this.cutoff()) throw invalid('消息已过期,未保存文件。');
258
+ await rename(temporary, path);
259
+ this.#db.prepare("UPDATE attachments SET status = 'ready', relative_path = ?, size_bytes = ?, last_error = '' WHERE id = ?")
260
+ .run(relativePath, size, attachment.id);
261
+ } catch (error) {
262
+ // A provider that ignores abort must not hold a download slot forever.
263
+ try { Promise.resolve(iterator?.return?.()).catch(() => {}); } catch {}
264
+ await handle?.close().catch(() => {});
265
+ await rm(temporary, { force: true }).catch(() => {});
266
+ this.#db.prepare("UPDATE attachments SET status = ?, last_error = ? WHERE id = ?")
267
+ .run(error.code === 'group-history-invalid' ? 'unavailable' : 'failed',
268
+ error.code === 'group-history-invalid' ? error.message : '文件下载失败或链接已过期。', attachment.id);
269
+ }
270
+ }
271
+
272
+ idle() { return this.#active.size || this.#jobs.size ? new Promise((done) => this.#idle.push(done)) : Promise.resolve(); }
273
+
274
+ async query(groupId, { kind = 'messages', from, to, keyword = '', cursor, limit = 100 } = {}) {
275
+ await this.ready();
276
+ if (this.#settingsError) throw invalid(this.#settingsError);
277
+ const group = this.#db.prepare('SELECT * FROM groups WHERE id = ?').get(groupId);
278
+ if (!group) throw invalid('当前群没有已保存记录。');
279
+ if (!['messages', 'files'].includes(kind)) throw invalid('查询类型无效。');
280
+ if (!Number.isInteger(limit) || limit < 1 || limit > 100) throw invalid('每页条数必须为 1–100。');
281
+ const lower = Math.max(this.cutoff(), from === undefined ? this.cutoff() : timestamp(from, NaN));
282
+ const upper = to === undefined ? this.#now() : timestamp(to, NaN);
283
+ if (!Number.isFinite(lower) || !Number.isFinite(upper) || lower > upper) throw invalid('时间范围无效。');
284
+ let after = [lower, ''];
285
+ if (cursor) {
286
+ try {
287
+ const data = JSON.parse(Buffer.from(cursor, 'base64url').toString());
288
+ if (data.groupId !== groupId || data.kind !== kind || !Number.isSafeInteger(data.time) || typeof data.id !== 'string') throw new Error();
289
+ after = [data.time, data.id];
290
+ } catch { throw invalid('分页游标无效。'); }
291
+ }
292
+ const table = kind === 'files' ? 'attachments a JOIN messages m ON m.id = a.message_id' : 'messages m';
293
+ const id = kind === 'files' ? 'a.id' : 'm.id';
294
+ const content = kind === 'files' ? 'a.name' : 'm.text';
295
+ const fields = kind === 'files' ? 'a.*, m.sent_at' : 'm.*';
296
+ const rows = this.#db.prepare(`SELECT ${fields} FROM ${table} WHERE m.group_id = ? AND m.sent_at >= ? AND m.sent_at <= ?
297
+ AND (m.sent_at > ? OR (m.sent_at = ? AND ${id} > ?)) AND instr(lower(${content}), lower(?)) > 0
298
+ ORDER BY m.sent_at, ${id} LIMIT ?`).all(groupId, lower, upper, after[0], after[0], after[1], text(keyword), limit + 1);
299
+ const items = []; let bytes = 0; let last;
300
+ for (const row of rows.slice(0, limit)) {
301
+ let item;
302
+ if (kind === 'files') item = { ...attachmentView(row), sentAt: row.sent_at };
303
+ else item = { id: row.id, senderId: row.sender_id, senderName: row.sender_name,
304
+ sentAt: row.sent_at, type: row.type, text: row.text.slice(0, 8000), textTruncated: row.text.length > 8000,
305
+ threadId: row.thread_id, replyToMessageId: row.reply_to_message_id,
306
+ attachments: this.#db.prepare('SELECT * FROM attachments WHERE message_id = ? ORDER BY source_attachment_key LIMIT 11').all(row.id).map(attachmentView) };
307
+ if (item.attachments?.length > 10) { item.attachments.pop(); item.attachmentsTruncated = true; }
308
+ // Bound even the first item, including UTF-8 text and many attachment names.
309
+ while (Buffer.byteLength(JSON.stringify(item)) > 20_000) {
310
+ if (item.attachments?.length) { item.attachments.pop(); item.attachmentsTruncated = true; }
311
+ else { item.text = item.text.slice(0, Math.floor(item.text.length / 2)); item.textTruncated = true; }
312
+ }
313
+ const length = Buffer.byteLength(JSON.stringify(item));
314
+ if (items.length && bytes + length > 20_000) break;
315
+ items.push(item); bytes += length; last = row;
316
+ }
317
+ return { groupName: group.name || group.platform_group_id, retentionDays: this.#days,
318
+ recordingStartedAt: group.recording_started_at, from: lower, to: upper, items,
319
+ nextCursor: last && rows.length > items.length ? Buffer.from(JSON.stringify({ groupId, kind, time: last.sent_at, id: last.id })).toString('base64url') : null,
320
+ coverage: 'Only messages actually received by this plugin; not complete platform history.' };
321
+ }
322
+
323
+ async materialize(groupId, attachmentId, workspace) {
324
+ await this.ready();
325
+ if (this.#settingsError) throw invalid(this.#settingsError);
326
+ const row = this.#db.prepare(`SELECT a.* FROM attachments a JOIN messages m ON m.id = a.message_id
327
+ WHERE a.id = ? AND m.group_id = ? AND m.sent_at >= ?`).get(attachmentId, groupId, this.cutoff());
328
+ if (!row || row.status !== 'ready' || !row.relative_path) throw invalid('该文件不属于当前群、已过期或尚未下载成功。');
329
+ if (typeof workspace !== 'string' || !workspace) throw invalid('当前会话没有可用的文件目录。');
330
+ const staged = await stageInboundFiles({ files: [{ name: row.name, mediaType: row.mime_type,
331
+ load: () => ({ stream: createReadStream(join(this.#root, row.relative_path)) }),
332
+ }] }, { workspace, retention: this.#copyService?.stagingRetention() ?? 'turn',
333
+ onStagedDirectory: this.#copyService ? (directory) => this.#copyService.trackDirectory(directory) : null });
334
+ const tracked = this.#copyService?.trackStaged(staged) ?? staged;
335
+ return { ...attachmentView(row), path: resolve(workspace, staged.files[0].path), cleanup: () => tracked.cleanup(),
336
+ note: 'Session copy. Read this file to inspect its contents; the shared original is unchanged.' };
337
+ }
338
+
339
+ sweep() {
340
+ if (this.#sweep) return this.#sweep;
341
+ this.#sweep = this.#maintenance.catch(() => {}).then(() => this.#sweepExpired()).finally(() => { this.#sweep = null; });
342
+ this.#maintenance = this.#sweep;
343
+ return this.#sweep;
344
+ }
345
+
346
+ async #sweepExpired() {
347
+ await this.ready();
348
+ if (this.#settingsError) return { deletedMessages: 0, error: this.#settingsError };
349
+ let deletedMessages = 0;
350
+ const cutoff = this.cutoff();
351
+ let after = [0, ''];
352
+ while (true) {
353
+ const rows = this.#db.prepare(`SELECT id,group_id,sent_at FROM messages WHERE sent_at < ?
354
+ AND (sent_at > ? OR (sent_at = ? AND id > ?)) ORDER BY sent_at,id LIMIT 500`).all(cutoff, after[0], after[0], after[1]);
355
+ if (!rows.length) break;
356
+ for (const message of rows) {
357
+ after = [message.sent_at, message.id];
358
+ const attachments = this.#db.prepare('SELECT id FROM attachments WHERE message_id = ?').all(message.id);
359
+ if (attachments.some((item) => this.#active.has(item.id))) continue;
360
+ for (const item of attachments) this.#jobs.delete(item.id);
361
+ try {
362
+ await rm(join(this.#root, 'group-files', message.group_id, message.id), { recursive: true, force: true });
363
+ this.#db.prepare('DELETE FROM messages WHERE id = ? AND sent_at < ?').run(message.id, cutoff);
364
+ deletedMessages += 1;
365
+ } catch (error) { this.#warn(error); }
366
+ }
367
+ }
368
+ return { deletedMessages };
369
+ }
370
+
371
+ close() { return this.#close ??= this.#shutdown(); }
372
+
373
+ async #shutdown() {
374
+ this.#closing = true;
375
+ clearInterval(this.#timer);
376
+ if (!this.#ready) return;
377
+ await this.ready();
378
+ await this.#maintenance.catch(() => {});
379
+ await this.idle();
380
+ await this.#sweep;
381
+ this.#db.close();
382
+ }
383
+ }
@@ -0,0 +1,56 @@
1
+ export function groupHistoryAttachments(message) {
2
+ const attachments = [];
3
+ for (const [type, sources] of [['image', message?.images], ['file', message?.files]]) {
4
+ for (const [index, source] of (sources ?? []).entries()) {
5
+ attachments.push({ ...source, key: `${type}:${index}`,
6
+ name: source.name ?? source.fileName ?? `${type}-${index + 1}`,
7
+ mediaType: source.mediaType ?? source.mimeType,
8
+ load: source.loadStream ?? source.load,
9
+ });
10
+ }
11
+ }
12
+ return attachments;
13
+ }
14
+
15
+ export function groupHistoryEntry(channel, raw, message, { scope = '', groupName } = {}) {
16
+ const common = { channel, scope, groupName, senderId: message.senderId,
17
+ senderName: message.contextSource?.()?.senderName, attachments: groupHistoryAttachments(message) };
18
+ if (channel === 'whatsapp') return { ...common, groupId: raw.key?.remoteJid,
19
+ messageId: raw.key?.id, sentAt: Number(raw.messageTimestamp) * 1000, text: message.content,
20
+ type: message.files?.length ? 'file' : message.images?.length ? 'image' : 'text' };
21
+ if (channel === 'telegram') {
22
+ const item = raw.message;
23
+ return { ...common, groupId: String(item.chat.id), groupName: item.chat.title,
24
+ messageId: String(item.message_id), sentAt: item.date * 1000, text: item.text ?? item.caption ?? '',
25
+ threadId: item.message_thread_id === undefined ? undefined : String(item.message_thread_id),
26
+ replyToMessageId: item.reply_to_message?.message_id === undefined ? undefined : String(item.reply_to_message.message_id),
27
+ type: item.document ? 'file' : item.photo ? 'image' : 'text',
28
+ capability: '关闭 Privacy Mode 或设为群管理员后才能接收普通群消息;只保存平台实际投递的消息。' };
29
+ }
30
+ if (channel === 'discord') return { ...common, scope: String(raw.guild_id ?? ''), groupId: raw.channel_id,
31
+ messageId: raw.id, sentAt: raw.timestamp, text: raw.content ?? '', type: raw.attachments?.length ? 'file' : 'text',
32
+ replyToMessageId: raw.message_reference?.message_id,
33
+ capability: '需要频道访问权限及 MESSAGE_CONTENT;未授权时正文和附件可能为空。' };
34
+ if (channel === 'slack') return { ...common, scope: raw.team_id ?? scope, groupId: raw.event.channel,
35
+ messageId: raw.event.ts, sentAt: Math.floor(Number(raw.event.ts) * 1000), text: raw.event.text ?? '',
36
+ type: raw.event.files?.length ? 'file' : 'text', threadId: raw.event.thread_ts,
37
+ capability: '需订阅 message.channels / message.groups,并已加入目标频道。' };
38
+ return null;
39
+ }
40
+
41
+ /** Record received groups before the response gate, without requiring a mention or an AI session. */
42
+ export async function captureGroupHistory(store, message, entry, { logger = console } = {}) {
43
+ if (!store || !entry || message?.kind !== 'group') return message;
44
+ try {
45
+ const context = await store.capture({ ...entry,
46
+ senderId: entry.senderId ?? message.senderId,
47
+ text: entry.text ?? message.content ?? '',
48
+ attachments: entry.attachments ?? groupHistoryAttachments(message),
49
+ });
50
+ // A context is a live service reference, not a model-controlled group selector.
51
+ if (context) message.groupHistory = context;
52
+ } catch (error) {
53
+ logger.warn?.('[dsh-im] unable to save group message:', error?.message ?? 'archive unavailable');
54
+ }
55
+ return message;
56
+ }
@@ -1,3 +1,4 @@
1
+ import { groupHistoryAccess } from './group-history-access.mjs';
1
2
  import { spawn } from 'node:child_process';
2
3
  import { randomUUID } from 'node:crypto';
3
4
  import { mkdir } from 'node:fs/promises';
@@ -1935,6 +1936,7 @@ export class HarnessClient {
1935
1936
  this.#registerControlOwnership(ownership);
1936
1937
  }
1937
1938
  // Advertise delivery only when this request can actually claim its files.
1939
+ const closeGroupHistoryAccess = groupHistoryAccess.open(sessionId, promptRpcId, options.groupHistory);
1938
1940
  const closeArtifactConsumer = typeof onArtifact === 'function'
1939
1941
  ? outboundArtifactRegistry.openConsumer(sessionId, promptRpcId)
1940
1942
  : null;
@@ -2185,6 +2187,7 @@ export class HarnessClient {
2185
2187
  }
2186
2188
  }
2187
2189
  closeArtifactConsumer?.();
2190
+ closeGroupHistoryAccess();
2188
2191
  if (ownership) {
2189
2192
  this.#unregisterControlOwnership(ownership);
2190
2193
  this.#unregisterInteractionOwnership(sessionId, ownership);
@@ -80,8 +80,8 @@ export default {
80
80
  '旧授权链接已作废,已生成新的修复链接。':
81
81
  'The previous authorization link was invalidated and a new repair link was generated.',
82
82
  '🔧 准备补全权限与回调。': '🔧 Preparing to complete permissions and the callback.',
83
- '本次会增量添加当前缺少项:卡片回调 card.action.trigger;飞书显示为“获取单聊、群组消息”的租户权限 im:message:readonly(用于读取用户消息中的图片或文件);im:resource(用于上传机器人发送的图片或文件);im:message.group_at_msg.include_bot:readonly(用于接收群内其他机器人 @ 当前机器人的消息);以及原生命令面板所需的 application:app_slash_command:read / write。确认页只会显示当前缺少的项;若出现上述范围之外的配置,请取消。':
84
- 'This incrementally adds the currently missing items: the card callback card.action.trigger; the tenant scope im:message:readonly, shown by Feishu as “Read direct and group messages” and used to read images or files in user messages; im:resource, used to upload images or files sent by the bot; im:message.group_at_msg.include_bot:readonly, used to receive group messages from other bots that mention this bot; and application:app_slash_command:read / write for the native command panel. The confirmation page shows only items the app is currently missing; cancel if anything outside this scope appears.',
83
+ '本次会增量添加当前缺少项:卡片回调 card.action.trigger;im:message.group_msg(用于接收未 @ 的群消息);飞书显示为“获取单聊、群组消息”的租户权限 im:message:readonly(用于读取用户消息中的图片或文件);im:resource(用于上传机器人发送的图片或文件);im:message.group_at_msg.include_bot:readonly(用于接收群内其他机器人 @ 当前机器人的消息);以及原生命令面板所需的 application:app_slash_command:read / write。群回复方式保持不变,实际收到的群消息和文件会自动保存。确认页只会显示当前缺少的项;若出现上述范围之外的配置,请取消。':
84
+ 'This incrementally adds the currently missing items: the card callback card.action.trigger; im:message.group_msg for group messages without mentions; the tenant scope im:message:readonly, shown by Feishu as “Read direct and group messages” and used to read images or files in user messages; im:resource, used to upload images or files sent by the bot; im:message.group_at_msg.include_bot:readonly, used to receive group messages from other bots that mention this bot; and application:app_slash_command:read / write for the native command panel. The group reply mode stays unchanged, and received group messages and files are saved automatically. The confirmation page shows only items the app is currently missing; cancel if anything outside this scope appears.',
85
85
  '当前设备直接打开:': 'Open directly on this device:',
86
86
  '若要用另一台设备扫码,发送 /repair qr。{expiry}。':
87
87
  'To scan with another device, send /repair qr. {expiry}.',
@@ -1286,6 +1286,7 @@ export class TextHarnessBridge {
1286
1286
  createOptions: this.#signal ? { signal: this.#signal } : undefined,
1287
1287
  existsOptions: this.#signal ? { signal: this.#signal } : undefined,
1288
1288
  askOptions: {
1289
+ groupHistory: message.groupHistory,
1289
1290
  timeoutMs: this.#replyTimeoutMs,
1290
1291
  signal: this.#signal,
1291
1292
  control: { owner: this, key: conversationKey },
@@ -29,6 +29,8 @@ settings:
29
29
  event_subscriptions:
30
30
  bot_events:
31
31
  - app_mention
32
+ - message.channels
33
+ - message.groups
32
34
  - message.im
33
35
  org_deploy_enabled: false
34
36
  socket_mode_enabled: true
@@ -1,3 +1,4 @@
1
+ import { captureGroupHistory, groupHistoryEntry } from '../shared/group-history.mjs';
1
2
  import { extractConnectionEvidence, createConnectionDiagnostics, atConnectionStage } from '../shared/connection-error.mjs';
2
3
  import { splitMessageText } from '../shared/editable-message-stream.mjs';
3
4
  import { chunkMarkdownParts } from '../shared/markdown-chunks.mjs';
@@ -167,7 +168,8 @@ export function normalizeSlackEvent(payload, botUserId, {
167
168
  if (!event || !payload?.event_id || !event.channel || !event.user || !event.ts) return null;
168
169
  const direct = event.type === 'message' && event.channel_type === 'im';
169
170
  const mentioned = event.type === 'app_mention';
170
- if (!direct && !mentioned) return null;
171
+ const group = event.type === 'message' && ['channel', 'group'].includes(event.channel_type);
172
+ if (!direct && !mentioned && !group) return null;
171
173
  if ((event.subtype && event.subtype !== 'file_share') || event.bot_id || event.app_id) return null;
172
174
  const threadTs = String(event.thread_ts ?? event.ts);
173
175
  const replyTo = slackThreadReplyReference(event, loadReply);
@@ -439,6 +441,7 @@ export class SlackRuntime {
439
441
  #harness;
440
442
  #state;
441
443
  #contextEnhancement;
444
+ #groupHistory;
442
445
  #accessPolicy;
443
446
  #logger;
444
447
  #diagnostics;
@@ -465,6 +468,7 @@ export class SlackRuntime {
465
468
  harness,
466
469
  state,
467
470
  contextEnhancement,
471
+ groupHistory,
468
472
  accessPolicy,
469
473
  logger = console,
470
474
  replyTimeoutMs = 600_000,
@@ -482,6 +486,7 @@ export class SlackRuntime {
482
486
  this.#harness = harness;
483
487
  this.#state = state;
484
488
  this.#contextEnhancement = contextEnhancement;
489
+ this.#groupHistory = groupHistory;
485
490
  this.#accessPolicy = accessPolicy;
486
491
  this.#logger = logger; this.#diagnostics = createConnectionDiagnostics({ channel: 'slack', logger });
487
492
  this.#replyTimeoutMs = replyTimeoutMs;
@@ -665,7 +670,10 @@ export class SlackRuntime {
665
670
  });
666
671
  const bridge = this.#bridge;
667
672
  if (message && bridge) {
668
- void bridge.accept(message).catch((error) => {
673
+ void captureGroupHistory(this.#groupHistory, message, groupHistoryEntry('slack', packet.payload, message, {
674
+ scope: this.#config.platformId.split(':')[0],
675
+ }), { logger: this.#logger })
676
+ .then(() => bridge.accept(message)).catch((error) => {
669
677
  if (generation !== this.#generation || this.#stopped) return;
670
678
  this.#logger.error?.(
671
679
  `[dsh-im:slack] bot ${this.#config.botId} message handling failed:`,
@@ -1,3 +1,4 @@
1
+ import { captureGroupHistory, groupHistoryEntry } from '../shared/group-history.mjs';
1
2
  import { extractConnectionEvidence, createConnectionDiagnostics, atConnectionStage } from '../shared/connection-error.mjs';
2
3
 
3
4
  import { createEditableMessageStream } from '../shared/editable-message-stream.mjs';
@@ -1107,6 +1108,7 @@ export class TelegramRuntime {
1107
1108
  #harness;
1108
1109
  #state;
1109
1110
  #contextEnhancement;
1111
+ #groupHistory;
1110
1112
  #accessPolicy;
1111
1113
  #logger;
1112
1114
  #diagnostics;
@@ -1136,6 +1138,7 @@ export class TelegramRuntime {
1136
1138
  harness,
1137
1139
  state,
1138
1140
  contextEnhancement,
1141
+ groupHistory,
1139
1142
  accessPolicy,
1140
1143
  logger = console,
1141
1144
  replyTimeoutMs = 600_000,
@@ -1151,6 +1154,7 @@ export class TelegramRuntime {
1151
1154
  this.#harness = harness;
1152
1155
  this.#state = state;
1153
1156
  this.#contextEnhancement = contextEnhancement;
1157
+ this.#groupHistory = groupHistory;
1154
1158
  this.#accessPolicy = accessPolicy;
1155
1159
  this.#logger = logger; this.#diagnostics = createConnectionDiagnostics({ channel: 'telegram', logger });
1156
1160
  this.#replyTimeoutMs = replyTimeoutMs;
@@ -1424,6 +1428,9 @@ export class TelegramRuntime {
1424
1428
  loadReplyContent: (reference, options) => this.#loadReplyContent(reference, options),
1425
1429
  });
1426
1430
  if (message) {
1431
+ await captureGroupHistory(this.#groupHistory, message, groupHistoryEntry('telegram', update, message), {
1432
+ logger: this.#logger,
1433
+ });
1427
1434
  void this.#bridge.accept(message, { contextSnapshot }).catch((error) => {
1428
1435
  if (signal.aborted) return;
1429
1436
  this.#logger.error?.(
@@ -1,3 +1,4 @@
1
+ import { captureGroupHistory, groupHistoryEntry } from '../shared/group-history.mjs';
1
2
  import { createConnectionDiagnostics, atConnectionStage } from '../shared/connection-error.mjs';
2
3
  import { createHash, randomBytes } from 'node:crypto';
3
4
 
@@ -724,6 +725,7 @@ export class WhatsappRuntime {
724
725
  #harness;
725
726
  #state;
726
727
  #contextEnhancement;
728
+ #groupHistory;
727
729
  #accessPolicy;
728
730
  #logger;
729
731
  #diagnostics;
@@ -744,6 +746,7 @@ export class WhatsappRuntime {
744
746
  harness,
745
747
  state,
746
748
  contextEnhancement,
749
+ groupHistory,
747
750
  accessPolicy,
748
751
  logger = console,
749
752
  replyTimeoutMs = 600_000,
@@ -759,6 +762,7 @@ export class WhatsappRuntime {
759
762
  this.#harness = harness;
760
763
  this.#state = state;
761
764
  this.#contextEnhancement = contextEnhancement;
765
+ this.#groupHistory = groupHistory;
762
766
  this.#accessPolicy = accessPolicy;
763
767
  this.#logger = logger; this.#diagnostics = createConnectionDiagnostics({ channel: 'whatsapp', logger });
764
768
  this.#replyTimeoutMs = replyTimeoutMs;
@@ -821,6 +825,22 @@ export class WhatsappRuntime {
821
825
  }),
822
826
  });
823
827
  if (!message || outboundIds.has(message.providerMessageId) || !this.#bridge) return;
828
+ let groupName;
829
+ if (this.#groupHistory && message.kind === 'group' && message.addressed) {
830
+ let timeout;
831
+ try {
832
+ groupName = (await Promise.race([
833
+ context?.socket?.groupMetadata?.(message.conversationId),
834
+ new Promise((resolve) => { timeout = setTimeout(resolve, 2500); timeout.unref?.(); }),
835
+ ]))?.subject;
836
+ } catch { /* optional metadata must not block normal replies */ }
837
+ finally { clearTimeout(timeout); }
838
+ }
839
+ if (!hasViewOnceWrapper(raw.message)) {
840
+ await captureGroupHistory(this.#groupHistory, message, groupHistoryEntry('whatsapp', raw, message, { groupName }), {
841
+ logger: this.#logger,
842
+ });
843
+ }
824
844
  this.#status.lastCheckedAt = Date.now();
825
845
  await this.#bridge.accept(message);
826
846
  },