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/qqapi.js ADDED
@@ -0,0 +1,420 @@
1
+ /**
2
+ * QQ OpenAPI client: access-token lifecycle and every HTTP endpoint the
3
+ * adapter uses — text/keyboard/typing/media messages (passive and active),
4
+ * small and chunked media upload, C2C stream frames, interaction acks, and a
5
+ * raw proxy for the agent-facing qq_api tool.
6
+ */
7
+ import { createHash } from 'node:crypto';
8
+ import { readFile, stat } from 'node:fs/promises';
9
+ import { MEDIA_TYPE } from './types.js';
10
+ const TOKEN_RETRY_MS = 10_000;
11
+ const REQUEST_TIMEOUT_MS = 30_000;
12
+ const UPLOAD_TIMEOUT_MS = 300_000;
13
+ /** QQ single-shot upload ceiling (base64 path); larger files go chunked. */
14
+ const MAX_DIRECT_UPLOAD_BYTES = 10 * 1024 * 1024;
15
+ /** Chunked-upload part-finish retry budget. */
16
+ const PART_FINISH_RETRIES = 3;
17
+ function asRecord(value) {
18
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
19
+ ? value
20
+ : undefined;
21
+ }
22
+ export class QQApiError extends Error {
23
+ status;
24
+ body;
25
+ constructor(message, status, body) {
26
+ super(message);
27
+ this.status = status;
28
+ this.body = body;
29
+ this.name = 'QQApiError';
30
+ }
31
+ }
32
+ /**
33
+ * Per-target message sequence in the 0..65535 range (QQ requirement).
34
+ *
35
+ * 修 D11:demo 用「时间戳异或随机」会产生碰撞;这里改全局单调递增(每次调用 +1,
36
+ * 模 65536),保证同一时刻内多次发送的 msg_seq 互不相同、单调,QQ 不再拒绝。
37
+ */
38
+ let seqCounter = 0;
39
+ export function nextMsgSeq() {
40
+ seqCounter = (seqCounter + 1) % 65_536;
41
+ return seqCounter;
42
+ }
43
+ export class QQApi {
44
+ config;
45
+ log;
46
+ token;
47
+ tokenRefresh;
48
+ refreshTimer;
49
+ disposed = false;
50
+ onTokenReady;
51
+ /** Effective OpenAPI base URL with the sandbox host prefix applied once. */
52
+ endpoint;
53
+ constructor(config, log, hooks) {
54
+ this.config = config;
55
+ this.log = log;
56
+ const raw = (config.endpoint ?? 'https://api.sgroup.qq.com').replace(/\/+$/, '');
57
+ this.endpoint = (config.sandbox ?? true) ? raw.replace(/^(https?:\/\/)/, '$1sandbox.') : raw;
58
+ this.onTokenReady = hooks?.onTokenReady;
59
+ }
60
+ /** QQ 开放平台 AppID(正式版 BotConfig 用 qqAppId/qqSecret)。 */
61
+ appId() { return this.config.qqAppId ?? this.config.id; }
62
+ appSecret() { return this.config.qqSecret ?? this.config.secret; }
63
+ resolveEndpoint() {
64
+ return this.endpoint;
65
+ }
66
+ get isDisposed() { return this.disposed; }
67
+ dispose() {
68
+ this.disposed = true;
69
+ if (this.refreshTimer !== undefined)
70
+ clearTimeout(this.refreshTimer);
71
+ }
72
+ /** Obtain a valid access token, refreshing when missing. */
73
+ async ensureToken() {
74
+ if (this.token !== undefined)
75
+ return this.token;
76
+ if (this.tokenRefresh === undefined) {
77
+ this.tokenRefresh = this.refreshToken().finally(() => { this.tokenRefresh = undefined; });
78
+ }
79
+ return this.tokenRefresh;
80
+ }
81
+ async refreshToken() {
82
+ if (this.disposed)
83
+ throw new Error('QQApi disposed');
84
+ // Print the AppID we're about to use so misconfiguration (typo'd id,
85
+ // wrong secret for the active id, sandbox-vs-prod mismatch) is obvious
86
+ // in the log without exposing the secret.
87
+ this.log.info('QQ token: requesting appAccessToken (appId=%s endpoint=%s sandbox=%s)', this.appId(), this.endpoint, String(this.config.sandbox ?? true));
88
+ const response = await fetch('https://bots.qq.com/app/getAppAccessToken', {
89
+ method: 'POST',
90
+ headers: { 'Content-Type': 'application/json' },
91
+ body: JSON.stringify({ appId: this.appId(), clientSecret: this.appSecret() }),
92
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
93
+ });
94
+ const data = asRecord(await response.json().catch(() => undefined));
95
+ if (!response.ok || typeof data?.access_token !== 'string') {
96
+ // QQ returns `code`/`message` on failure (e.g. 400004 for appId mismatch);
97
+ // surface them so we can tell "wrong secret" from "unknown appId" from
98
+ // "app not approved".
99
+ const code = typeof data?.code === 'number' ? data.code : undefined;
100
+ const message = typeof data?.message === 'string' ? data.message : undefined;
101
+ throw new QQApiError(`token request failed: HTTP ${response.status}`
102
+ + (code !== undefined ? ` code=${code}` : '')
103
+ + (message !== undefined ? ` message=${message}` : '')
104
+ + ` (appId=${this.appId()})`, response.status, data);
105
+ }
106
+ this.token = data.access_token;
107
+ const expiresIn = typeof data.expires_in === 'number' ? data.expires_in : 300;
108
+ this.scheduleRefresh(Math.max(60, expiresIn - 60) * 1_000);
109
+ this.onTokenReady?.();
110
+ return this.token;
111
+ }
112
+ scheduleRefresh(delayMs) {
113
+ if (this.disposed)
114
+ return;
115
+ if (this.refreshTimer !== undefined)
116
+ clearTimeout(this.refreshTimer);
117
+ this.refreshTimer = setTimeout(() => {
118
+ this.refreshTimer = undefined;
119
+ this.token = undefined;
120
+ void this.ensureToken().catch((error) => {
121
+ this.log.error('QQ token refresh failed: %o', error);
122
+ this.refreshTimer = setTimeout(() => {
123
+ this.refreshTimer = undefined;
124
+ this.token = undefined;
125
+ void this.ensureToken().catch(() => undefined);
126
+ }, TOKEN_RETRY_MS);
127
+ });
128
+ }, delayMs);
129
+ }
130
+ /** Authenticated raw request used by every method and by the qq_api tool. */
131
+ async request(method, path, body, options) {
132
+ const attempt = async (tok) => {
133
+ const url = new URL(`${this.resolveEndpoint()}${path}`);
134
+ for (const [key, value] of Object.entries(options?.query ?? {}))
135
+ url.searchParams.set(key, value);
136
+ const response = await fetch(url, {
137
+ method,
138
+ headers: {
139
+ Authorization: `QQBot ${tok}`,
140
+ ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}),
141
+ },
142
+ body: body !== undefined ? JSON.stringify(body) : undefined,
143
+ signal: AbortSignal.timeout(options?.timeoutMs ?? REQUEST_TIMEOUT_MS),
144
+ });
145
+ const text = await response.text();
146
+ let parsed;
147
+ try {
148
+ parsed = text.length > 0 ? JSON.parse(text) : undefined;
149
+ }
150
+ catch {
151
+ parsed = text;
152
+ }
153
+ return { response, text, parsed };
154
+ };
155
+ const token = await this.ensureToken();
156
+ let result = await attempt(token);
157
+ // QQ 沙箱 token 偶发在取出后短期即失效(缓存仍持旧值,REST 被 401 拒),
158
+ // 而 getAppAccessToken 每次都拿新值。401 时强制刷新缓存并重试一次,
159
+ // 避免把「AccessToken无效或过期」透出给用户;重试仍失败则按原样抛错。
160
+ if (result.response.status === 401 && this.token === token) {
161
+ this.token = undefined;
162
+ if (this.refreshTimer !== undefined)
163
+ clearTimeout(this.refreshTimer);
164
+ const fresh = await this.refreshToken();
165
+ result = await attempt(fresh);
166
+ }
167
+ if (!result.response.ok) {
168
+ throw new QQApiError(`QQ ${method} ${path} failed: HTTP ${result.response.status} ${result.text.slice(0, 300)}`, result.response.status, result.parsed);
169
+ }
170
+ return result.parsed;
171
+ }
172
+ // ── Message senders ────────────────────────────────────────────────────────
173
+ messagePath(target, msgId) {
174
+ const path = target.kind === 'c2c'
175
+ ? `/v2/users/${target.userId}/messages`
176
+ : target.kind === 'group'
177
+ ? `/v2/groups/${target.groupId}/messages`
178
+ : `/channels/${target.channelId}/messages`;
179
+ return { path, body: msgId !== undefined ? { msg_id: msgId } : {} };
180
+ }
181
+ /** Send a plain or markdown text; returns the message id. */
182
+ async sendText(target, text, passiveMsgId) {
183
+ const { path, body } = this.messagePath(target, passiveMsgId);
184
+ const payload = this.config.markdown
185
+ ? { ...body, msg_type: 2, markdown: { content: text }, msg_seq: nextMsgSeq() }
186
+ : { ...body, msg_type: 0, content: text, msg_seq: nextMsgSeq() };
187
+ const result = asRecord(await this.request('POST', path, payload));
188
+ return typeof result?.id === 'string' ? result.id : undefined;
189
+ }
190
+ /** Send a text with an inline keyboard (approval buttons). */
191
+ async sendKeyboard(target, text, buttons, passiveMsgId) {
192
+ const { path, body } = this.messagePath(target, passiveMsgId);
193
+ await this.request('POST', path, {
194
+ ...body,
195
+ msg_type: 0,
196
+ content: text,
197
+ msg_seq: nextMsgSeq(),
198
+ keyboard: {
199
+ content: {
200
+ rows: [{
201
+ buttons: buttons.map((button) => ({
202
+ id: button.id,
203
+ render_data: { label: button.label, visited_label: button.visitedLabel, style: button.style },
204
+ action: { type: 1, data: button.data, permission: { type: 2 }, click_limit: 1 },
205
+ group_id: this.config.keyboardGroupId ?? 'dshqq',
206
+ })),
207
+ }],
208
+ },
209
+ },
210
+ });
211
+ }
212
+ /** Send the C2C typing indicator (valid ~60s; callers keep it alive). */
213
+ async sendTyping(target, passiveMsgId, seconds = 60) {
214
+ if (target.kind !== 'c2c' || passiveMsgId === undefined)
215
+ return;
216
+ await this.request('POST', `/v2/users/${target.userId}/messages`, {
217
+ msg_type: 6,
218
+ input_notify: { input_type: 1, input_second: seconds },
219
+ msg_seq: nextMsgSeq(),
220
+ msg_id: passiveMsgId,
221
+ }).catch((error) => {
222
+ // Typing is best-effort; QQ rejects it for stale anchors.
223
+ this.log.debug?.('typing send skipped: %o', error);
224
+ });
225
+ }
226
+ /** Acknowledge an INTERACTION_CREATE event after resolving its button. */
227
+ async ackInteraction(interactionId, code = 0) {
228
+ await this.request('PUT', `/interactions/${interactionId}`, { code });
229
+ }
230
+ // ── Media upload & send ────────────────────────────────────────────────────
231
+ uploadPath(target, suffix) {
232
+ const base = target.kind === 'c2c'
233
+ ? `/v2/users/${target.userId}`
234
+ : target.kind === 'group'
235
+ ? `/v2/groups/${target.groupId}`
236
+ : `/channels/${target.channelId}`;
237
+ return `${base}/${suffix}`;
238
+ }
239
+ /**
240
+ * Upload one media object and send it as a message.
241
+ * `source` may be an https URL, a data: URL, or an absolute local path
242
+ * (large local files automatically use the chunked pipeline).
243
+ */
244
+ async sendMedia(target, kind, source, options) {
245
+ const { path, body } = this.messagePath(target, options?.passiveMsgId);
246
+ // Guild channels have no files endpoint: images post through the message
247
+ // body's `image` URL field; other kinds fall back to a descriptive text.
248
+ if (target.kind === 'channel') {
249
+ if (kind === 'image' && /^https?:\/\//.test(source)) {
250
+ const result = asRecord(await this.request('POST', path, {
251
+ ...body,
252
+ content: options?.text ?? '',
253
+ image: source,
254
+ }, { timeoutMs: REQUEST_TIMEOUT_MS }));
255
+ const id = asRecord(result?.ext_info);
256
+ return { fileId: typeof id?.ref_idx === 'string' ? id.ref_idx : undefined };
257
+ }
258
+ throw new QQApiError(`guild-channel media only supports images via https URL (got ${kind}: ${source.slice(0, 60)})`, 0, undefined);
259
+ }
260
+ const file = await this.resolveMediaSource(target, source, kind);
261
+ const payload = {
262
+ ...body,
263
+ msg_type: 7,
264
+ media: { file_info: file.fileInfo },
265
+ msg_seq: nextMsgSeq(),
266
+ ...(options?.text !== undefined && options.text.length > 0 ? { content: options.text } : {}),
267
+ };
268
+ const result = asRecord(await this.request('POST', path, payload, { timeoutMs: UPLOAD_TIMEOUT_MS }));
269
+ const id = asRecord(result?.ext_info);
270
+ return { fileId: typeof id?.ref_idx === 'string' ? id.ref_idx : undefined };
271
+ }
272
+ async resolveMediaSource(target, source, kind) {
273
+ if (source.startsWith('https://') || source.startsWith('http://')) {
274
+ return this.directUpload(target, kind, { url: source });
275
+ }
276
+ if (source.startsWith('data:')) {
277
+ const comma = source.indexOf(',');
278
+ const base64 = comma >= 0 ? source.slice(comma + 1) : source;
279
+ return this.directUpload(target, kind, { fileData: base64, fileName: 'upload' });
280
+ }
281
+ // Local path: read size to choose direct vs chunked.
282
+ const info = await stat(source);
283
+ if (info.size <= MAX_DIRECT_UPLOAD_BYTES) {
284
+ const data = await readFile(source);
285
+ return this.directUpload(target, kind, {
286
+ fileData: data.toString('base64'),
287
+ fileName: source.split('/').pop() ?? 'file',
288
+ });
289
+ }
290
+ return this.chunkedUpload(target, kind, source);
291
+ }
292
+ /** Small-file upload: POST url or base64 body to the files endpoint. */
293
+ async directUpload(target, kind, input) {
294
+ const body = {
295
+ file_type: MEDIA_TYPE[kind],
296
+ srv_send_msg: false,
297
+ ...(input.url !== undefined ? { url: input.url } : {}),
298
+ ...(input.fileData !== undefined ? { file_data: input.fileData } : {}),
299
+ ...(kind === 'file' && input.fileName !== undefined ? { file_name: input.fileName } : {}),
300
+ };
301
+ const result = asRecord(await this.request('POST', this.uploadPath(target, 'files'), body, { timeoutMs: UPLOAD_TIMEOUT_MS }));
302
+ if (typeof result?.file_info !== 'string') {
303
+ throw new QQApiError('media upload returned no file_info', 0, result);
304
+ }
305
+ return { fileInfo: result.file_info };
306
+ }
307
+ /**
308
+ * Chunked upload for large local files:
309
+ * upload_prepare (hashes) → PUT parts to presigned URLs → upload_part_finish
310
+ * → complete. Concurrency follows the prepare response (capped at 10).
311
+ */
312
+ async chunkedUpload(target, kind, filePath) {
313
+ const fileSize = (await stat(filePath)).size;
314
+ const fileName = filePath.split('/').pop() ?? 'file';
315
+ const { md5, sha1, md5TenM } = await hashFile(filePath);
316
+ const prepare = asRecord(await this.request('POST', this.uploadPath(target, 'upload_prepare'), {
317
+ file_type: MEDIA_TYPE[kind],
318
+ file_name: fileName,
319
+ file_size: fileSize,
320
+ md5,
321
+ sha1,
322
+ md5_10m: md5TenM,
323
+ }, { timeoutMs: UPLOAD_TIMEOUT_MS }));
324
+ const uploadId = typeof prepare?.upload_id === 'string' ? prepare.upload_id : undefined;
325
+ const parts = Array.isArray(prepare?.parts) ? prepare.parts : undefined;
326
+ const blockSize = typeof prepare?.block_size === 'number' ? prepare.block_size : undefined;
327
+ if (uploadId === undefined || parts === undefined || blockSize === undefined || blockSize <= 0) {
328
+ throw new QQApiError('upload_prepare returned an unusable payload', 0, prepare);
329
+ }
330
+ const concurrency = Math.min(typeof prepare?.concurrency === 'number' ? prepare.concurrency : 1, 10);
331
+ let cursor = 0;
332
+ const failures = [];
333
+ const workers = Array.from({ length: concurrency }, async () => {
334
+ for (;;) {
335
+ const slot = cursor++;
336
+ if (slot >= parts.length || failures.length > 0)
337
+ return;
338
+ const part = parts[slot];
339
+ try {
340
+ await this.uploadPart(filePath, part.index, blockSize, fileSize, part.presigned_url, target, uploadId);
341
+ }
342
+ catch (error) {
343
+ failures.push(error);
344
+ return;
345
+ }
346
+ }
347
+ });
348
+ await Promise.all(workers);
349
+ if (failures.length > 0)
350
+ throw failures[0];
351
+ const complete = asRecord(await this.request('POST', this.uploadPath(target, 'files'), { upload_id: uploadId }, { timeoutMs: UPLOAD_TIMEOUT_MS }));
352
+ if (typeof complete?.file_info !== 'string') {
353
+ throw new QQApiError('chunked complete returned no file_info', 0, complete);
354
+ }
355
+ return { fileInfo: complete.file_info };
356
+ }
357
+ async uploadPart(filePath, partIndex, blockSize, fileSize, presignedUrl, target, uploadId) {
358
+ const offset = (partIndex - 1) * blockSize;
359
+ const length = Math.min(blockSize, fileSize - offset);
360
+ const handle = await readFile(filePath);
361
+ const partBuffer = handle.subarray(offset, offset + length);
362
+ const md5 = createHash('md5').update(partBuffer).digest('hex');
363
+ const put = await fetch(presignedUrl, {
364
+ method: 'PUT',
365
+ body: partBuffer,
366
+ signal: AbortSignal.timeout(UPLOAD_TIMEOUT_MS),
367
+ });
368
+ if (!put.ok)
369
+ throw new QQApiError(`part ${partIndex} PUT failed: HTTP ${put.status}`, put.status, undefined);
370
+ let attempt = 0;
371
+ for (;;) {
372
+ try {
373
+ await this.request('POST', this.uploadPath(target, 'upload_part_finish'), { upload_id: uploadId, part_index: partIndex, block_size: length, md5 }, { timeoutMs: UPLOAD_TIMEOUT_MS });
374
+ return;
375
+ }
376
+ catch (error) {
377
+ attempt += 1;
378
+ if (attempt > PART_FINISH_RETRIES)
379
+ throw error;
380
+ await new Promise((resolve) => setTimeout(resolve, attempt * 1000));
381
+ }
382
+ }
383
+ }
384
+ // ── C2C streaming ──────────────────────────────────────────────────────────
385
+ /** Send one replace-mode stream frame; returns the assigned stream msg id. */
386
+ async sendStreamFrame(userId, frame) {
387
+ const body = {
388
+ input_mode: 'replace',
389
+ input_state: frame.state,
390
+ content_type: 'markdown',
391
+ content_raw: frame.text,
392
+ event_id: frame.msgId,
393
+ msg_id: frame.msgId,
394
+ msg_seq: frame.msgSeq,
395
+ index: frame.index,
396
+ };
397
+ if (frame.streamMsgId !== undefined)
398
+ body.stream_msg_id = frame.streamMsgId;
399
+ const result = asRecord(await this.request('POST', `/v2/users/${userId}/stream_messages`, body, { timeoutMs: REQUEST_TIMEOUT_MS }));
400
+ return typeof result?.id === 'string' ? result.id : undefined;
401
+ }
402
+ /** Fetch the WebSocket gateway URL. */
403
+ async gatewayUrl() {
404
+ const result = asRecord(await this.request('GET', '/gateway'));
405
+ if (typeof result?.url !== 'string')
406
+ throw new QQApiError('gateway response missing url', 0, result);
407
+ return result.url;
408
+ }
409
+ }
410
+ /** File digests required by upload_prepare: md5, sha1, and md5 of the first ~10MB. */
411
+ async function hashFile(filePath) {
412
+ const data = await readFile(filePath);
413
+ const tenM = 10_002_432;
414
+ return {
415
+ md5: createHash('md5').update(data).digest('hex'),
416
+ sha1: createHash('sha1').update(data).digest('hex'),
417
+ md5TenM: createHash('md5').update(data.subarray(0, tenM)).digest('hex'),
418
+ };
419
+ }
420
+ //# sourceMappingURL=qqapi.js.map
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Persisted quote index: LRU of recent messages keyed by QQ `msg_idx`,
3
+ * appended as JSONL with compaction. When a user replies to a message the
4
+ * inbound event carries `ref_msg_idx`; resolve it from this store or fall
5
+ * back to the event's own `msg_elements[0]` copy of the quoted content.
6
+ */
7
+ import { appendFile, mkdir, readFile, rename, writeFile } from 'node:fs/promises';
8
+ import { dirname } from 'node:path';
9
+ const DEFAULT_MAX_ENTRIES = 5_000;
10
+ const COMPACT_RATIO = 2;
11
+ export class RefIndexStore {
12
+ file;
13
+ maxEntries;
14
+ entries = new Map();
15
+ writeChain = Promise.resolve();
16
+ constructor(file, maxEntries = DEFAULT_MAX_ENTRIES) {
17
+ this.file = file;
18
+ this.maxEntries = maxEntries;
19
+ }
20
+ /** Replay the JSONL log and compact when it exceeds the budget. */
21
+ async init() {
22
+ let lines;
23
+ try {
24
+ lines = (await readFile(this.file, 'utf8')).split('\n');
25
+ }
26
+ catch {
27
+ return;
28
+ }
29
+ const disk = [];
30
+ for (const line of lines) {
31
+ if (line.trim().length === 0)
32
+ continue;
33
+ try {
34
+ disk.push(JSON.parse(line));
35
+ }
36
+ catch {
37
+ // Torn tail line from a crash; ignore it.
38
+ }
39
+ }
40
+ disk.sort((a, b) => a.t - b.t);
41
+ for (const { k, v } of disk)
42
+ this.entries.set(k, v);
43
+ while (this.entries.size > this.maxEntries) {
44
+ const oldest = this.entries.keys().next().value;
45
+ if (oldest === undefined)
46
+ break;
47
+ this.entries.delete(oldest);
48
+ }
49
+ if (disk.length > this.maxEntries * COMPACT_RATIO)
50
+ await this.compact();
51
+ }
52
+ get(key) {
53
+ if (key === undefined)
54
+ return undefined;
55
+ const entry = this.entries.get(key);
56
+ if (entry !== undefined) {
57
+ // LRU refresh.
58
+ this.entries.delete(key);
59
+ this.entries.set(key, entry);
60
+ }
61
+ return entry;
62
+ }
63
+ set(key, entry) {
64
+ if (this.entries.size >= this.maxEntries) {
65
+ const oldest = this.entries.keys().next().value;
66
+ if (oldest !== undefined)
67
+ this.entries.delete(oldest);
68
+ }
69
+ this.entries.set(key, entry);
70
+ const line = JSON.stringify({ k: key, v: entry, t: Date.now() }) + '\n';
71
+ this.writeChain = this.writeChain.then(() => appendFile(this.file, line, 'utf8'), () => appendFile(this.file, line, 'utf8'));
72
+ }
73
+ /** Rewrite the store as one clean JSONL file (atomic tmp + rename). */
74
+ async compact() {
75
+ await mkdir(dirname(this.file), { recursive: true });
76
+ const ordered = [...this.entries.entries()];
77
+ const body = ordered.map(([k, v]) => JSON.stringify({ k, v, t: Date.now() })).join('\n') + '\n';
78
+ const tmp = `${this.file}.tmp`;
79
+ await writeFile(tmp, body, 'utf8');
80
+ await rename(tmp, this.file);
81
+ }
82
+ }
83
+ //# sourceMappingURL=refindex.js.map
@@ -0,0 +1,140 @@
1
+ /**
2
+ * Pygmalion 会话日志读取:从 dsh session.jsonl.zstd 程序化提取真实消息原文。
3
+ *
4
+ * dsh 把会话日志写为「多个 zstd frame 拼接」的 .jsonl.zstd(每个 frame 一段追加)。
5
+ * 本模块:
6
+ * 1) 按 zstd 帧魔数(28 b5 2f fd)切分;
7
+ * 2) 每帧用 node:zlib zstdDecompressSync 解压后拼接;
8
+ * 3) 逐行解析 JSON 事件,供 extractMessages 提取 user/assistant 原文。
9
+ *
10
+ * 文件路径:~/.dsh/sessions/<workspace-sanitized>/<sessionId(urlencoded)>/session.jsonl.zstd
11
+ */
12
+ import { zstdDecompressSync } from 'node:zlib';
13
+ import { readFile } from 'node:fs/promises';
14
+
15
+ const ZSTD_MAGIC = Buffer.from([0x28, 0xb5, 0x2f, 0xfd]);
16
+
17
+ /** 按 zstd 帧魔数把 buffer 切成多个独立帧(每帧可独立解压)。 */
18
+ export function zstdFrames(buffer) {
19
+ const starts = [];
20
+ for (let i = 0; i <= buffer.length - 4; i++) {
21
+ if (buffer[i] === ZSTD_MAGIC[0] && buffer[i + 1] === ZSTD_MAGIC[1]
22
+ && buffer[i + 2] === ZSTD_MAGIC[2] && buffer[i + 3] === ZSTD_MAGIC[3])
23
+ starts.push(i);
24
+ }
25
+ if (starts.length === 0) return [buffer];
26
+ const out = [];
27
+ for (let k = 0; k < starts.length; k++)
28
+ out.push(buffer.subarray(starts[k], k + 1 < starts.length ? starts[k + 1] : buffer.length));
29
+ return out;
30
+ }
31
+
32
+ /** 读取并解压一个会话文件,返回完整文本。 */
33
+ export async function readSessionText(file) {
34
+ const buf = await readFile(file);
35
+ return Buffer.concat(zstdFrames(buf).map((f) => zstdDecompressSync(f))).toString('utf8');
36
+ }
37
+
38
+ /** 解析 jsonl 文本为事件对象数组(忽略空行/坏行)。 */
39
+ export function parseEvents(text) {
40
+ const out = [];
41
+ for (const line of text.split('\n')) {
42
+ const l = line.trim();
43
+ if (!l) continue;
44
+ try { out.push(JSON.parse(l)); } catch { /* skip */ }
45
+ }
46
+ return out;
47
+ }
48
+
49
+ /** 从事件里取用户消息文本(agent/inbox/spliced → inserted[].role=user → 文本块)。 */
50
+ export function extractUserMessages(events) {
51
+ const out = [];
52
+ for (const ev of events) {
53
+ if (ev?.type === 'agent/inbox/spliced' && Array.isArray(ev.data?.inserted)) {
54
+ for (const m of ev.data.inserted) {
55
+ if (m?.role !== 'user') continue;
56
+ const text = (m.content || []).filter((b) => b.type === 'text').map((b) => b.text).join('');
57
+ if (text && text.trim()) out.push({ id: m.id, time: ev.time, text });
58
+ }
59
+ }
60
+ }
61
+ return out;
62
+ }
63
+
64
+ /** 模型侧上下文行(固定结构,非用户原话):[时间线] 时间戳行、[生活脚本] 非零提示行、[已下载附件:…] 行。 */
65
+ const CONTEXT_LINE = /^\[(?:时间线|生活脚本)\]/;
66
+
67
+ /** 剥离模型侧包装([时间线]…、[生活脚本]…、[已下载附件:…]、[引用消息开始]…),只留用户原话。 */
68
+ export function cleanUserText(raw) {
69
+ let out = String(raw ?? '')
70
+ .replace(/\[引用消息开始\][\s\S]*?\[引用消息结束\]/g, '')
71
+ .split('\n')
72
+ .map((l) => l.trim())
73
+ .filter((l) => l.length > 0 && !CONTEXT_LINE.test(l) && !/^\[已下载附件:/.test(l))
74
+ .join('\n');
75
+ return out.trim();
76
+ }
77
+
78
+ /** dsh 系统注入(非真实对话)识别:runtime context / 审批策略等。 */
79
+ const SYSTEM_PATTERNS = [
80
+ /^Current runtime context/im,
81
+ /Current DSH file policy/im,
82
+ /Approval policy: ask/im,
83
+ /^This snapshot supersedes/im,
84
+ ];
85
+
86
+ /** 是否系统注入文本(不归档为对话原文)。 */
87
+ export function isSystemText(text) {
88
+ const t = String(text ?? '');
89
+ return SYSTEM_PATTERNS.some((re) => re.test(t)) || t.length > 400;
90
+ }
91
+
92
+ /** QQ 官方 C2C openid:32 位十六进制(真实用户消息的结构标识;[sys] 等系统注入无此 id)。 */
93
+ const QQ_OPENID_RE = /^[0-9A-F]{32}$/;
94
+
95
+ /**
96
+ * 真实 QQ 用户消息白名单:`data.source` 必须 `kind='user'` 且 `id` 为 QQ openid
97
+ * (32 位十六进制)。其余一律不提取——包括 source 缺失、kind 非 user、以及
98
+ * source.kind='user' 但无 openid id 的系统注入(如管理页/测试入口发的 `[sys]...`)。
99
+ * 修 D19:旧实现是黑名单(仅排除已知注入保留字),`[sys]服务器重启…` 等漏进聊天记录。
100
+ */
101
+ export function isRealUserMessage(ev) {
102
+ const src = ev?.data?.source;
103
+ if (src === undefined || src.kind !== 'user') return false;
104
+ return typeof src.id === 'string' && QQ_OPENID_RE.test(src.id);
105
+ }
106
+
107
+ /**
108
+ * 从会话事件中提取完整对话原文(按时间排序、去重):
109
+ * - 用户消息:`user/message`(唯一来源,规避 spliced 双计),
110
+ * 以 source 固定结构判定真人(排除唤醒/HTTP 推送/系统快照),并过滤系统注入;
111
+ * - 角色消息:`tool/call` 中 name === 'director_send' 的 arguments.messages(实际发出的消息)。
112
+ * 返回 [{ role: 'user'|'character', time, text }]。
113
+ */
114
+ export function extractMessages(events) {
115
+ const userSeen = new Set();
116
+ const msgs = [];
117
+ const push = (role, time, text) => {
118
+ const clean = cleanUserText(text);
119
+ if (!clean || isSystemText(clean)) return;
120
+ msgs.push({ role, time: Number(time) || undefined, text: clean });
121
+ };
122
+ for (const ev of events) {
123
+ if (ev?.type === 'user/message' && isRealUserMessage(ev) && Array.isArray(ev.data?.content)) {
124
+ const t = ev.data.content.filter((b) => b.type === 'text').map((b) => b.text).join('');
125
+ // 按消息 id 去重(同 id 才是同一消息);无 id 时按 时间+文本 兜底。
126
+ // 不按文本单独去重:同一句话在不同时刻发送是真实的多条消息,必须都记(避免漏)。
127
+ const key = ev.data.id ?? `${ev.time}|${cleanUserText(t)}`;
128
+ if (userSeen.has(key)) continue;
129
+ userSeen.add(key);
130
+ push('user', ev.time, t);
131
+ } else if (ev?.type === 'tool/call' && ev.data?.name === 'director_send') {
132
+ try {
133
+ const args = JSON.parse(ev.data.arguments ?? '{}');
134
+ for (const m of Array.isArray(args.messages) ? args.messages : []) push('character', ev.time, m);
135
+ } catch { /* skip malformed */ }
136
+ }
137
+ }
138
+ msgs.sort((a, b) => (a.time ?? 0) - (b.time ?? 0));
139
+ return msgs;
140
+ }