dsh-wechat-access 0.0.0-stage → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/LICENSE +675 -0
  3. package/README.md +278 -2
  4. package/cordis.patch.yml +5 -0
  5. package/examples/config.example.json +98 -0
  6. package/index.mjs +123 -0
  7. package/lib/access.mjs +131 -0
  8. package/lib/anysearch.mjs +143 -0
  9. package/lib/capabilities.mjs +312 -0
  10. package/lib/client.js +2532 -0
  11. package/lib/config.mjs +509 -0
  12. package/lib/emotion-store.mjs +352 -0
  13. package/lib/emotion.mjs +428 -0
  14. package/lib/endocrine/LICENSE +21 -0
  15. package/lib/endocrine/README.md +39 -0
  16. package/lib/endocrine/diseases.js +791 -0
  17. package/lib/endocrine/engine.mjs +131 -0
  18. package/lib/endocrine/store.mjs +253 -0
  19. package/lib/endocrine/upstream.mjs +1230 -0
  20. package/lib/group-gate.mjs +305 -0
  21. package/lib/imagegen.mjs +360 -0
  22. package/lib/lock.mjs +204 -0
  23. package/lib/meme-classify.mjs +190 -0
  24. package/lib/memes.mjs +442 -0
  25. package/lib/memory.mjs +437 -0
  26. package/lib/normalize.mjs +230 -0
  27. package/lib/parser.mjs +602 -0
  28. package/lib/reply-settled.mjs +130 -0
  29. package/lib/runtime.mjs +3367 -0
  30. package/lib/startup.mjs +70 -0
  31. package/lib/steam-binding.mjs +144 -0
  32. package/lib/steam.mjs +334 -0
  33. package/lib/store.mjs +259 -0
  34. package/lib/thoughts.mjs +149 -0
  35. package/lib/time-context.mjs +182 -0
  36. package/lib/tools.mjs +583 -0
  37. package/lib/ui.mjs +997 -0
  38. package/lib/util.mjs +489 -0
  39. package/lib/virtual-life-generate.mjs +421 -0
  40. package/lib/virtual-life.mjs +971 -0
  41. package/lib/weather.mjs +172 -0
  42. package/lib/wechat-client.mjs +476 -0
  43. package/lib/wechat-events.mjs +269 -0
  44. package/locale/zh.json +6 -0
  45. package/package.json +77 -4
package/lib/store.mjs ADDED
@@ -0,0 +1,259 @@
1
+ import { appendFile, mkdir, open, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ import {Mutex, assert, checkSignal, digest, jsonClone, isoDate } from './util.mjs';
5
+
6
+ export { acquireLock, LockHeldError, lockOwnerAlive, lockOwnerFresh } from './lock.mjs';
7
+
8
+ async function atomicJson(path, data) {
9
+ const temp = `${path}.${randomUUID()}.tmp`;
10
+ const handle = await open(temp, 'wx', 0o600);
11
+ try { await handle.writeFile(JSON.stringify(data)); await handle.sync(); }
12
+ finally { await handle.close(); }
13
+ try { await rename(temp, path); }
14
+ finally { await rm(temp, { force: true }); }
15
+ }
16
+
17
+ async function tailLines(path, limitBytes = 16 * 1024 * 1024) {
18
+ const file = await open(path, 'r');
19
+ try {
20
+ const { size } = await file.stat();
21
+ const start = Math.max(0, size - limitBytes);
22
+ const bytes = Buffer.alloc(size - start);
23
+ await file.read(bytes, 0, bytes.length, start);
24
+ let text = bytes.toString('utf8');
25
+ if (start > 0) text = text.slice(text.indexOf('\n') + 1);
26
+ return { lines: text.split('\n').filter(Boolean).reverse(), truncated: start > 0 };
27
+ } finally { await file.close(); }
28
+ }
29
+
30
+ const messageKey = m => `${m.selfId}:${m.kind}:${m.peerId}:${m.direction}:${m.messageId}`;
31
+
32
+ export class MessageStore {
33
+ #mutex = new Mutex();
34
+ #seen = new Set();
35
+ #conversations = new Map();
36
+ // E1:query 是热路径(每次回复 + 每次主动 tick 都调)。归档文件只会追加,
37
+ // 用 stat 的 size+mtimeMs 做失效键即可安全复用解析结果;prune 删文件后
38
+ // stat 会 ENOENT,自然回落到读取路径(不存在则按空处理)。
39
+ #lineCache = new Map();
40
+ async #tailLinesCached(path) {
41
+ let meta;
42
+ try { meta = await stat(path); }
43
+ catch (e) { if (e.code === 'ENOENT') return null; throw e; }
44
+ const key = `${meta.size}:${meta.mtimeMs}`;
45
+ const cached = this.#lineCache.get(path);
46
+ if (cached && cached.key === key) return cached.value;
47
+ const value = await tailLines(path);
48
+ this.#lineCache.set(path, { key, value });
49
+ // 只保留最近 8 个文件:单份上限 16MB,8 份足以覆盖任何查询窗口。
50
+ if (this.#lineCache.size > 8) {
51
+ const first = this.#lineCache.keys().next().value;
52
+ this.#lineCache.delete(first);
53
+ }
54
+ return value;
55
+ }
56
+ constructor(dataDir, retentionDays) { this.dir = join(dataDir, 'messages'); this.retentionDays = retentionDays; this.appended = 0; }
57
+ async init() {
58
+ await mkdir(this.dir, { recursive: true, mode: 0o700 });
59
+ await this.prune();
60
+ const recent = await this.query({ limit: 50_000, days: this.retentionDays });
61
+ for (const m of recent.messages) this.#remember(m);
62
+ this.indexTruncated = recent.truncated;
63
+ }
64
+ #remember(message) {
65
+ this.#seen.add(messageKey(message));
66
+ // 超过上限时淘汰最旧的一条。这只影响内存去重集合,所以还不够 ——
67
+ // 被淘汰的 message_id 若再次被推送(重连、轮询补漏),append() 会认为它是新消息,
68
+ // accept() 于是再排一次回复,用户看到第二条。
69
+ // 真正的兜底在 append() 里:靠归档文件回查,见 #archiveHas()。
70
+ if (this.#seen.size > 500_000) this.#seen.delete(this.#seen.values().next().value);
71
+ const key = `${message.kind}:${message.peerId}`;
72
+ const old = this.#conversations.get(key);
73
+ if (!old || old.time <= message.time) this.#conversations.set(key, {
74
+ kind: message.kind, peerId: message.peerId, time: message.time,
75
+ // lastAt 是毫秒(给面板排序和「最近活跃」用)。
76
+ // time 是 Unix 秒,直接喂给 new Date() 会落到 1970 年 ——
77
+ // 而 ui.mjs 读的是 lastAt,那个字段以前根本不存在,
78
+ // 于是面板里每条都显示「无活跃记录」、排序也全是 0。
79
+ lastAt: Number(message.time) * 1000,
80
+ lastText: message.text.slice(0, 100), nickname: message.nickname,
81
+ });
82
+ }
83
+ /**
84
+ * 当天归档里有没有这条消息(内存去重集合的兜底)。
85
+ *
86
+ * 归档是 `YYYY-MM-DD.jsonl` 一行一条。只查当天的文件:
87
+ * 回放的都是最近的重复推送,查全量文件会拖慢每条消息。
88
+ */
89
+ async #archiveHas(message) {
90
+ const id = String(message?.messageId ?? '').trim();
91
+ if (!id) return false;
92
+ const file = join(this.dir, `${isoDate(new Date())}.jsonl`);
93
+ let text;
94
+ try { text = await readFile(file, 'utf8'); }
95
+ catch { return false; }
96
+ const kind = message.kind;
97
+ const peerId = String(message.peerId ?? '');
98
+ const needle = `"messageId":"${id}"`;
99
+ // E3:绝大多数 append 都不是重复消息。先做一次整段 includes(无分配),
100
+ // 只有确实出现这个 id 时才 split+逐行解析。今日归档 63 行时扫描从
101
+ // 0.020ms 降到 0.0025ms;日志越大收益越明显。
102
+ if (!text.includes(needle)) return false;
103
+ for (const line of text.split('\n')) {
104
+ if (!line.includes(needle)) continue;
105
+ try {
106
+ const m = JSON.parse(line);
107
+ if (m.kind === kind && String(m.peerId) === peerId) return true;
108
+ } catch { /* 半截行(正在写):忽略 */ }
109
+ }
110
+ return false;
111
+ }
112
+
113
+ append(message) {
114
+ return this.#mutex.run(async () => {
115
+ if (this.#seen.has(messageKey(message))) return false;
116
+ // 内存去重集合有上限,被淘汰的旧 id 会漏过去。
117
+ // 落盘前再回查一次当天归档:同一条消息不应该被回复两次。
118
+ if (await this.#archiveHas(message)) { this.#seen.add(messageKey(message)); return false; }
119
+ const entry = jsonClone(message);
120
+ // Archive by receipt date, not an untrusted sender-supplied timestamp.
121
+ // 用本地日期切文件:UTC 会让东八区凌晨的消息落进前一天。
122
+ const date = isoDate(new Date());
123
+ await appendFile(join(this.dir, `${date}.jsonl`), JSON.stringify(entry) + '\n', { mode: 0o600 });
124
+ this.#remember(entry);
125
+ this.appended += 1;
126
+ return true;
127
+ });
128
+ }
129
+ async prune() {
130
+ // 0 = 永久保存:不设 cutoff,也就不删任何一天。
131
+ if (!(this.retentionDays > 0)) return;
132
+ const cutoff = Date.now() - this.retentionDays * 86_400_000;
133
+ for (const name of await readdir(this.dir)) {
134
+ if (/^\d{4}-\d{2}-\d{2}\.jsonl$/.test(name) && Date.parse(name.slice(0, 10)) + 86_400_000 < cutoff) await rm(join(this.dir, name));
135
+ }
136
+ }
137
+ conversations() { return [...this.#conversations.values()].sort((a, b) => b.time - a.time); }
138
+ async query({ kind, peerId, keyword = '', limit = 50, days = this.retentionDays, direction = '', signal } = {}) {
139
+ checkSignal(signal);
140
+ const names = (await readdir(this.dir)).filter(n => /^\d{4}-\d{2}-\d{2}\.jsonl$/.test(n)).sort().reverse();
141
+ // days = 0 表示永久保存:用 -Infinity 作为下限,任何日期文件都不会被跳过。
142
+ const cutoff = days > 0 ? Date.now() - days * 86_400_000 : -Infinity;
143
+ let scanned = 0, truncated = false, corruptLines = 0;
144
+ const messages = [];
145
+ outer: for (const name of names) {
146
+ checkSignal(signal);
147
+ if (Date.parse(name.slice(0, 10)) + 86_400_000 < cutoff) continue;
148
+ let file;
149
+ try { file = await this.#tailLinesCached(join(this.dir, name)); }
150
+ catch (e) { if (e.code === 'ENOENT') continue; throw e; }
151
+ if (!file) continue;
152
+ truncated ||= file.truncated;
153
+ for (const line of file.lines) {
154
+ checkSignal(signal);
155
+ if (++scanned > 100_000) { truncated = true; break outer; }
156
+ let m;
157
+ try { m = JSON.parse(line); }
158
+ catch { corruptLines++; continue; }
159
+ if (!m || typeof m.text !== 'string') { corruptLines++; continue; }
160
+ // direction 过滤必须发生在计入 limit 之前。
161
+ //
162
+ // 撤回工具要在「最近 50 条」里找她自己的出站消息。热闹的群里,
163
+ // 两分钟内可能进来 50 条别人的话,她刚才那条直接被挤出窗口 ——
164
+ // 于是「撤不回自己刚发的消息」。先按方向过滤,limit 才真的是「最近 N 条我发的」。
165
+
166
+ if (direction && m.direction !== direction) continue;
167
+ if ((kind && m.kind !== kind) || (peerId && m.peerId !== peerId) || (keyword ? !m.text.toLocaleLowerCase().includes(keyword.toLocaleLowerCase()) : false)) continue;
168
+ messages.push(m);
169
+ if (messages.length >= limit) { truncated = true; break outer; }
170
+ }
171
+ }
172
+ return {
173
+ messages: messages.reverse(), scanned, truncated, corruptLines, source: 'local_archive',
174
+ direction: direction || 'both',
175
+ retentionDays: this.retentionDays,
176
+ retention: this.retentionDays > 0 ? `最近 ${this.retentionDays} 天` : '永久保存(不按天清理)',
177
+ };
178
+ }
179
+ }
180
+
181
+ export class ActionLedger {
182
+ #mutex = new Mutex();
183
+ #entries = new Map();
184
+ constructor(dataDir) { this.path = join(dataDir, 'action-receipts.json'); }
185
+ async init() {
186
+ try {
187
+ const entries = JSON.parse(await readFile(this.path, 'utf8'));
188
+ assert(Array.isArray(entries), '操作记录损坏');
189
+ for (const entry of entries) this.#entries.set(entry.requestId, entry);
190
+ } catch (error) { if (error.code !== 'ENOENT') throw error; }
191
+ }
192
+ async #save() {
193
+ while (this.#entries.size > 10_000) this.#entries.delete(this.#entries.keys().next().value);
194
+ await atomicJson(this.path, [...this.#entries.values()]);
195
+ }
196
+ async run(requestId, payload, operation) {
197
+ const hash = digest(payload);
198
+ // 同一个 request_id 再来一次,按上次的结果分别处理:
199
+ //
200
+ // sent → 真的发过了,短路(这正是去重的目的)
201
+ // uncertain → 可能已经送到 QQ,只差没拿到 message_id;宁可漏发也不能重发
202
+ // failed → 确定被拒绝,什么都没发出去,**必须允许重做**
203
+ // busy → 根本没开始(被在途锁挡回),什么都没发出去,**必须允许重做**
204
+ // pending → 上次执行到一半进程被杀;超时后允许重做,没超时说明还在跑
205
+ //
206
+ // 以前不区分,只要有条目就短路。于是「确定失败」也被当成「已处理」,
207
+ // 而 reply() 又不看 status —— 用户永远收不到这条,额度还在烧。
208
+ const pendingTimeoutMs = Math.max(30_000, Number(this.pendingTimeoutMs ?? 120_000));
209
+ const prior = await this.#mutex.run(async () => {
210
+ const entry = this.#entries.get(requestId);
211
+ if (entry) {
212
+ const retriable = entry.status === 'failed'
213
+ // busy = 上一次压根没开始做(被在途锁挡回去了),什么都没发出去。
214
+ // 不放进可重试名单的话,模型拿着同一个 request_id 重试会命中
215
+ // 下面的 duplicate 短路,永远拿回同一个 busy —— 看起来像「重试无效」。
216
+ || entry.status === 'busy'
217
+ || (entry.status === 'pending' && Date.now() - entry.time > pendingTimeoutMs);
218
+ // 先判断能不能重做,再判断内容是否一致。
219
+ //
220
+ // 顺序反了会有个很难受的后果:发送失败后模型往往会改写措辞再试
221
+ //(「我下楼买点东西」→「我去楼下买点东西」),
222
+ // 而旧代码先断言哈希相同,于是永远卡在「同一 request_id 不能用于不同内容」,
223
+ // 这一轮剩下的段也一起发不出去。
224
+ //
225
+ // failed / 超时 pending:允许换正文重做(上一次没发出去,换句话是正常的)
226
+ // sent:换正文仍然要拒绝(同一个编号不能把另一段话发给同一个人)
227
+ // uncertain:不重做,也不抛错(可能已经发出去了,重发会出两条)
228
+ // pending 未超时:不重做,内容变了才报错(正发着的时候换内容说不通)
229
+ if (retriable) {
230
+ // 允许覆盖。下面会写入新的 payloadHash。
231
+ } else {
232
+ if (entry.status === 'uncertain') {
233
+ // 不确定有没有发出去:短路,且绝不能抛 —— 抛了会让恢复逻辑每轮撞一次,
234
+ // 模型被反复调用而消息还是发不出去。
235
+ return { ...entry, duplicate: true };
236
+ }
237
+ assert(entry.payloadHash === hash, '同一 request_id 不能用于不同内容或目标');
238
+ return { ...entry, duplicate: true };
239
+ }
240
+ }
241
+ this.#entries.set(requestId, { requestId, payloadHash: hash, status: 'pending', time: Date.now() });
242
+ try { await this.#save(); }
243
+ catch (error) { this.#entries.delete(requestId); throw error; }
244
+ return null;
245
+ });
246
+ if (prior) return prior;
247
+ try {
248
+ const result = await operation();
249
+ const entry = { requestId, payloadHash: hash, status: result.status ?? 'sent', time: Date.now(), result: jsonClone(result) };
250
+ await this.#mutex.run(async () => { this.#entries.set(requestId, entry); await this.#save(); });
251
+ return entry;
252
+ } catch (error) {
253
+ const status = ['OneBotRejectedError', 'NotSubmittedError'].includes(error.name) ? 'failed' : 'uncertain';
254
+ const entry = { requestId, payloadHash: hash, status, time: Date.now() };
255
+ await this.#mutex.run(async () => { this.#entries.set(requestId, entry); await this.#save(); });
256
+ throw error;
257
+ }
258
+ }
259
+ }
@@ -0,0 +1,149 @@
1
+ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+
4
+ const VERSION = 1;
5
+ // 每人最多留多少条。念头是「最近在想什么」,不是完整日记:
6
+ // 太多会把提示词挤满,而且一个月前的念头和现在的对话已经无关。
7
+ const MAX_PER_PERSON = 40;
8
+
9
+ /**
10
+ * 「想过但没说出口」的内容。
11
+ *
12
+ * 模型的 reasoning 只活在宿主会话里。会话一被回收(或进程重启),
13
+ * 那部分就没了 —— 于是她「刚才想过要问的事」下一轮就不记得了。
14
+ *
15
+ * 归档 messages/ 存的是真正发出去的文字,记忆存的是对方说过的话,
16
+ * 两者都补不上这个缺口。所以这里单独存一份。
17
+ *
18
+ * 和记忆的区别:
19
+ * 记忆 = 对方告诉我的事(第三人称,客观)
20
+ * 念头 = 我自己想的事(第一人称,内心活动)
21
+ * 混在一起会让注入的提示词分不清「他说过」和「我想过」。
22
+ */
23
+ export class ThoughtStore {
24
+ constructor({ dataDir, logger = console, limit = MAX_PER_PERSON } = {}) {
25
+ this.root = join(dataDir, 'thoughts');
26
+ this.file = join(this.root, 'thoughts.json');
27
+ this.logger = logger;
28
+ this.limit = Math.max(1, Number(limit) || MAX_PER_PERSON);
29
+ // { [personId]: [{ at, text, source }] },越靠后越新。
30
+ this.people = {};
31
+ this.loaded = false;
32
+ this.writeChain = Promise.resolve();
33
+ }
34
+
35
+ async init() {
36
+ if (this.loaded) return this;
37
+ await mkdir(this.root, { recursive: true });
38
+ try {
39
+ const raw = JSON.parse(await readFile(this.file, 'utf8'));
40
+ if (raw?.version === VERSION && raw.people && typeof raw.people === 'object') {
41
+ this.people = raw.people;
42
+ }
43
+ } catch { /* 文件不存在或坏了就从空开始 */ }
44
+ this.loaded = true;
45
+ return this;
46
+ }
47
+
48
+ #save() {
49
+ this.writeChain = this.writeChain.then(async () => {
50
+ await mkdir(this.root, { recursive: true });
51
+ const tmp = this.file + '.tmp';
52
+ await writeFile(tmp, JSON.stringify({ version: VERSION, people: this.people }, null, 2) + '\n');
53
+ await rename(tmp, this.file);
54
+ }).catch((error) => this.logger.warn?.('念头写入失败:' + error.message));
55
+ return this.writeChain;
56
+ }
57
+
58
+ /** 某人最近的念头,新的在前。 */
59
+ list(personId, { limit = 5, maxAgeHours = 48, now = Date.now() } = {}) {
60
+ const key = String(personId ?? '').trim();
61
+ if (!key) return [];
62
+ const cutoff = now - Math.max(1, maxAgeHours) * 3600_000;
63
+ // people[key] 的历史形状有两种:
64
+ // 旧:{ thoughts: [...] }(早期版本写的)
65
+ // 新:[...](当前 #save 写的)
66
+ // 只认数组会让旧文件在 list() 里抛 "all.filter is not a function",
67
+ // 而它在 reply() 里被调用 —— 一次异常就能打断整轮回复。
68
+ const all = arrayOf(this.people[key]);
69
+ return all
70
+ .filter((t) => Number(t.at) >= cutoff)
71
+ .slice(-Math.max(1, limit))
72
+ .reverse();
73
+ }
74
+
75
+ /**
76
+ * 记一批念头。
77
+ *
78
+ * 同一个人短时间内可能产生很多段 reasoning(多步工具调用)。
79
+ * 这里按内容去重,并且只留最后 limit 条 —— 否则一次长任务就能塞满。
80
+ */
81
+ async remember(personId, thoughts, { source = '', now = Date.now() } = {}) {
82
+ const key = String(personId ?? '').trim();
83
+ if (!key) return 0;
84
+ const incoming = (Array.isArray(thoughts) ? thoughts : [thoughts])
85
+ .map((t) => String(t ?? '').replace(/\s+/g, ' ').trim())
86
+ // 太短的多半是「好的」「让我看看」这类过程话,存下来没有价值。
87
+ .filter((t) => t.length >= 8)
88
+ .slice(0, 10);
89
+ if (!incoming.length) return 0;
90
+
91
+ const list = arrayOf(this.people[key]);
92
+ const seen = new Set(list.map((t) => t.text));
93
+ let added = 0;
94
+ for (const text of incoming) {
95
+ if (seen.has(text)) continue;
96
+ seen.add(text);
97
+ list.push({ at: now, text: text.slice(0, 400), source: String(source).slice(0, 40) });
98
+ added += 1;
99
+ }
100
+ if (!added) return 0;
101
+ this.people[key] = list.slice(-this.limit);
102
+ await this.#save();
103
+ return added;
104
+ }
105
+
106
+ async flush() { await this.writeChain; }
107
+ }
108
+
109
+ /**
110
+ * 把念头拼成提示词片段。
111
+ *
112
+ * 必须明确要求「不要复述」:不写的话模型会把内心独白当台词念出来,
113
+ * 或者生硬地提「我之前想过……」—— 那是人设崩塌,不是自然对话。
114
+ */
115
+ export function renderThoughtBlock({ thoughts = [], now = Date.now() } = {}) {
116
+ if (!thoughts.length) return '';
117
+ const lines = [
118
+ '你自己最近想过这些(是你的内心活动,不要复述、不要说「我之前想过」,自然地带进对话就好):',
119
+ ];
120
+ for (const thought of thoughts) {
121
+ const when = formatWhen(thought.at, now);
122
+ lines.push('- ' + (when ? when + ':' : '') + thought.text);
123
+ }
124
+ return lines.join('\n');
125
+ }
126
+
127
+
128
+ /**
129
+ * 把 people[key] 归一成数组。
130
+ *
131
+ * 早期版本写进去的是 { thoughts: [...] },后来改成直接存数组。
132
+ * 两种都可能出现在磁盘上,读的时候统一一下,写出去永远是新形状。
133
+ * 读到既不是数组也不是 { thoughts } 的脏数据时返回空数组,不抛错 ——
134
+ * 这个函数在回复路径上被调用,抛一次就会毁掉整轮对话。
135
+ */
136
+ function arrayOf(value) {
137
+ if (Array.isArray(value)) return value;
138
+ if (value && Array.isArray(value.thoughts)) return value.thoughts;
139
+ return [];
140
+ }
141
+ function formatWhen(at, now) {
142
+ const ms = Number(at);
143
+ if (!Number.isFinite(ms) || ms <= 0) return '';
144
+ const diff = Math.max(0, now - ms);
145
+ if (diff < 3600_000) return Math.max(1, Math.round(diff / 60_000)) + ' 分钟前';
146
+ if (diff < 86400_000) return Math.round(diff / 3600_000) + ' 小时前';
147
+ const d = new Date(ms);
148
+ return (d.getMonth() + 1) + '-' + d.getDate();
149
+ }
@@ -0,0 +1,182 @@
1
+ /**
2
+ * Time context for chat history.
3
+ *
4
+ * The bug this fixes: `recent_messages` was sent to the model with sender, text
5
+ * and direction but no time at all. The model saw a flat list of turns and had no
6
+ * way to tell "you said this two minutes ago" from "you said this last Tuesday",
7
+ * so it treated every archived line as if it had just been said. The observable
8
+ * symptom is her answering an old message as though it were the current topic.
9
+ *
10
+ * Two design rules, both learned from what models actually do with timestamps:
11
+ *
12
+ * - RELATIVE FIRST, ABSOLUTE SECOND. A raw epoch or an ISO string forces the
13
+ * model to do date arithmetic, which it does badly. "3 天前" is what a person
14
+ * would say and needs no computation. The absolute clock is still included so
15
+ * that "上周三" style references remain answerable.
16
+ *
17
+ * - THE GAP IS MORE IMPORTANT THAN THE STAMP. A message from 6 days ago that is
18
+ * one line above the current message reads as continuous conversation. So the
19
+ * gap since the previous turn is emitted as its own field, and a long gap gets
20
+ * an explicit marker the model cannot miss.
21
+ */
22
+
23
+ /** Time-of-day bucket, used only to pick a natural phrasing. */
24
+ function partOfDay(date) {
25
+ const h = date.getHours();
26
+ if (h < 5) return '凌晨';
27
+ if (h < 8) return '早上';
28
+ if (h < 11) return '上午';
29
+ if (h < 13) return '中午';
30
+ if (h < 17) return '下午';
31
+ if (h < 19) return '傍晚';
32
+ if (h < 23) return '晚上';
33
+ return '深夜';
34
+ }
35
+
36
+ const pad = (n) => String(n).padStart(2, '0');
37
+
38
+ /** `YYYY-MM-DD HH:MM` in local time. */
39
+ export function absoluteTime(value) {
40
+ const date = toDate(value);
41
+ if (!date) return '';
42
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
43
+ }
44
+
45
+ /**
46
+ * Accept epoch seconds, epoch milliseconds, Date, or a parseable string.
47
+ *
48
+ * QQ timestamps arrive in seconds; anything already in milliseconds is detected
49
+ * by magnitude. Getting this wrong shifts every message by decades, so the
50
+ * heuristic is deliberately generous at the boundary (year 2286 in seconds).
51
+ */
52
+ export function toDate(value) {
53
+ if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value;
54
+ const n = Number(value);
55
+ if (Number.isFinite(n) && n > 0) {
56
+ // Anything below ~1e11 is seconds (1e11 s ≈ year 5138; 1e11 ms ≈ 1973).
57
+ const ms = n < 1e11 ? n * 1000 : n;
58
+ const date = new Date(ms);
59
+ return Number.isNaN(date.getTime()) ? null : date;
60
+ }
61
+ if (typeof value === 'string' && value.trim()) {
62
+ const date = new Date(value);
63
+ return Number.isNaN(date.getTime()) ? null : date;
64
+ }
65
+ return null;
66
+ }
67
+
68
+ /** Whole days between two calendar dates (not 24h periods). */
69
+ function calendarDaysBetween(a, b) {
70
+ const da = new Date(a.getFullYear(), a.getMonth(), a.getDate());
71
+ const db = new Date(b.getFullYear(), b.getMonth(), b.getDate());
72
+ return Math.round((db - da) / 86_400_000);
73
+ }
74
+
75
+ /**
76
+ * Human-readable distance into the past.
77
+ *
78
+ * Deliberately coarse: "刚刚" / "5 分钟前" / "2 小时前" / "3 天前" / "上个月".
79
+ * Precision beyond that adds tokens without changing how the model should behave.
80
+ */
81
+ export function relativeTime(value, now = new Date()) {
82
+ const date = toDate(value);
83
+ if (!date) return '';
84
+ const diffMs = now.getTime() - date.getTime();
85
+ if (diffMs < 0) {
86
+ const ahead = -diffMs;
87
+ if (ahead < 60_000) return '刚刚';
88
+ if (ahead < 3_600_000) return `${Math.round(ahead / 60_000)} 分钟后`;
89
+ return `${Math.round(ahead / 3_600_000)} 小时后`;
90
+ }
91
+ const minutes = Math.floor(diffMs / 60_000);
92
+ if (minutes < 1) return '刚刚';
93
+ if (minutes < 60) return `${minutes} 分钟前`;
94
+
95
+ const hours = Math.floor(minutes / 60);
96
+ const days = calendarDaysBetween(date, now);
97
+
98
+ // Same calendar day: prefer hours so "3 小时前" beats a vague "今天".
99
+ if (days === 0) return `${hours} 小时前`;
100
+ if (days === 1) return `昨天${partOfDay(date)}`;
101
+ if (days === 2) return `前天${partOfDay(date)}`;
102
+ if (days < 7) return `${days} 天前`;
103
+ if (days < 30) return `${Math.floor(days / 7)} 周前`;
104
+ if (days < 365) return `${Math.floor(days / 30)} 个月前`;
105
+ return `${Math.floor(days / 365)} 年前`;
106
+ }
107
+
108
+ /**
109
+ * A gap long enough that the conversation should be treated as restarted.
110
+ *
111
+ * Two hours is the point where "continuing the same thread" stops being a
112
+ * reasonable assumption for casual chat.
113
+ */
114
+ export const LONG_GAP_MINUTES = 120;
115
+
116
+ /**
117
+ * Duration of the silence before a message, or '' when it is continuous.
118
+ *
119
+ * This describes a LENGTH, not a point in time. Returning `relativeTime` here was
120
+ * a real bug: "上一轮是 3 小时前,中间隔了 3 小时前" — the same fact twice, and
121
+ * the second half is not even grammatical. A duration is what the sentence needs.
122
+ */
123
+ export function gapDescription(previousValue, currentValue) {
124
+ const prev = toDate(previousValue);
125
+ const cur = toDate(currentValue);
126
+ if (!prev || !cur) return '';
127
+ const minutes = Math.floor((cur.getTime() - prev.getTime()) / 60_000);
128
+ if (minutes < 1) return '';
129
+ if (minutes < 60) return `${minutes} 分钟`;
130
+ const hours = Math.floor(minutes / 60);
131
+ if (hours < 24) return `${hours} 小时`;
132
+ const days = calendarDaysBetween(prev, cur);
133
+ if (days < 7) return `${days} 天`;
134
+ if (days < 30) return `${Math.floor(days / 7)} 周`;
135
+ if (days < 365) return `${Math.floor(days / 30)} 个月`;
136
+ return `${Math.floor(days / 365)} 年`;
137
+ }
138
+
139
+ /**
140
+ * Build the per-message time fields to attach to a history row.
141
+ *
142
+ * `previous` is the timestamp of the row before this one, so a long silence can
143
+ * be surfaced inline. Returns an empty object when the timestamp is unusable, so
144
+ * callers can spread it unconditionally.
145
+ */
146
+ export function timeFields(value, { now = new Date(), previous = null } = {}) {
147
+ const date = toDate(value);
148
+ if (!date) return {};
149
+ const gap = previous ? gapDescription(previous, date) : '';
150
+ return {
151
+ time: absoluteTime(date),
152
+ ago: relativeTime(date, now),
153
+ ...(gap ? { since_previous: gap } : {}),
154
+ };
155
+ }
156
+
157
+ /**
158
+ * A one-line "now" header for the whole input.
159
+ *
160
+ * Without this the model has to infer the current time from the newest message,
161
+ * which is exactly the inference that fails after a long silence.
162
+ */
163
+ export function nowLine(now = new Date()) {
164
+ const date = toDate(now) ?? new Date();
165
+ const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
166
+ return `${absoluteTime(date)} ${weekdays[date.getDay()]}(${partOfDay(date)})`;
167
+ }
168
+
169
+ /**
170
+ * Flag a conversation that has been idle long enough to need re-orienting.
171
+ *
172
+ * Returns null when the last exchange was recent, otherwise a sentence the model
173
+ * can act on. This is the difference between "she picks up where she left off"
174
+ * and "she answers a week-old question as if it were asked now".
175
+ */
176
+ export function idleNotice(lastValue, now = new Date(), { thresholdMinutes = LONG_GAP_MINUTES } = {}) {
177
+ const last = toDate(lastValue);
178
+ if (!last) return null;
179
+ const minutes = Math.floor((now.getTime() - last.getTime()) / 60_000);
180
+ if (minutes < thresholdMinutes) return null;
181
+ return `上一轮对话是${relativeTime(last, now)}(${absoluteTime(last)}),中间隔了 ${gapDescription(last, now)}。`;
182
+ }