whale-memory-core 0.18.2 → 0.19.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.
package/index.d.ts CHANGED
@@ -14,3 +14,6 @@ export * as chapterEvents from './lib/chapter-events.js'
14
14
  export * as book from './lib/book.js'
15
15
  export * as unsaid from './lib/unsaid.js'
16
16
  export * as archive from './lib/archive.js'
17
+ export * as timeSense from './lib/time-sense.js'
18
+ export * as relativeWindow from './lib/relative-window.js'
19
+ export * as personCard from './lib/person-card.js'
package/index.js CHANGED
@@ -16,3 +16,7 @@ export * as chapterEvents from './lib/chapter-events.js'
16
16
  export * as book from './lib/book.js'
17
17
  export * as unsaid from './lib/unsaid.js'
18
18
  export * as archive from './lib/archive.js'
19
+ export * as timeSense from './lib/time-sense.js'
20
+ export * as relativeWindow from './lib/relative-window.js'
21
+ export * as personCard from './lib/person-card.js'
22
+ export * as scopeKey from './lib/scope-key.js'
@@ -0,0 +1,4 @@
1
+ /** 把一个人的档案压成一行提示词;信息不足返回空串 */
2
+ export function renderPersonCard(card: Record<string, unknown>, options?: { now?: number; minEvidence?: number }): string
3
+ /** 挑当前说话人那张卡;默认不按"话最多"退回别人 */
4
+ export function pickPersonCard(cards: Array<Record<string, unknown>>, speaker?: { personId?: string; chatKey?: string }, options?: { fallback?: boolean }): Record<string, unknown> | null
@@ -0,0 +1,179 @@
1
+ /**
2
+ * 人物卡:把「这个人是谁、你们聊过什么、最近一次」压成一行,供提示词使用。
3
+ *
4
+ * 为什么需要:她的记忆是「事件」和「片段」,没有「人」这一层。
5
+ * 问她"某某是谁",她能翻到提到过这个名字的片段,但拼不出这个人是谁。
6
+ *
7
+ * 纯函数,不读文件、不调模型;数据由调用方传进来。
8
+ *
9
+ * 两轮审查后收紧的地方:
10
+ * 1. 群聊不退回别人;精确匹配要带会话,避免同一个人跨群取错卡
11
+ * 2. 关系阶段要有证据支撑(证据条数 < 3 不写)
12
+ * 3. 名字清洗只针对真乱码,不剥合法英文前缀(Tom小明 保持完整)
13
+ * 4. 名字和例句里的分隔符要净化:否则昵称写成「X:关系:挚友」就能伪造卡片
14
+ * 5. 时间戳兼容秒级;「刚认识」只用于当天
15
+ */
16
+
17
+ /** 全角/半角里能伪造卡片结构的符号,从名字里去掉。 */
18
+ const BIDI = /[\u200e\u200f\u202a-\u202e\u2066-\u2069]/g;
19
+ const NAME_BREAKERS = /[::,,。.;;、||「」『』“”"'\n\r\t\u2028\u2029]/g;
20
+
21
+ import { humanTime } from './time-sense.js';
22
+
23
+ /** 名字里的控制字符、零宽字符一律清掉。 */
24
+ function cleanName(value) {
25
+ return String(value || '')
26
+ .replace(/[\u0000-\u001f\u007f\u0080-\u009f\u200b-\u200f\ufeff]/g, '')
27
+ .replace(BIDI, '')
28
+ .replace(/^[^\p{L}\p{N}]+/u, '') // 开头的符号去掉
29
+ .replace(NAME_BREAKERS, '')
30
+ .replace(/\s+/g, ' ')
31
+ .trim();
32
+ }
33
+
34
+ /**
35
+ * 只处理真乱码:名字开头连续 2 个以上 Latin-1 补充字符、且后面跟着汉字时,
36
+ * 把这段剥掉(如「ÿfÌÿ地形雨…」→「地形雨…」)。
37
+ * 合法的「Tom小明」「Ame酱」不含这类字符,不会被剥。
38
+ */
39
+ function stripMojibakePrefix(name) {
40
+ const cjkAt = name.search(/[\u3400-\u9fff]/);
41
+ if (cjkAt <= 0) return name;
42
+ const prefix = name.slice(0, cjkAt);
43
+ if (prefix.length > 8) return name;
44
+ const latin1 = [...prefix].filter((c) => c >= '\u00c0' && c <= '\u00ff').length;
45
+ // 只有"前面夹了两个以上 Latin-1 补充字符"才当乱码;Tom小明、Ame酱 这类合法名不受影响
46
+ return latin1 >= 2 ? name.slice(cjkAt) : name;
47
+ }
48
+
49
+ /** 「傻鱼(¬_¬)」→「傻鱼」:去掉结尾的括号注释。 */
50
+ function baseName(value) {
51
+ const first = String(value || '').split(' / ')[0];
52
+ const cleaned = cleanName(stripMojibakePrefix(cleanName(first)));
53
+ return cleaned.replace(/[((][^()()]{0,8}[))]$/, '').trim();
54
+ }
55
+
56
+ /** 名字是否还能用:有字,且没有控制/替换字符。 */
57
+ function nameIsUsable(name) {
58
+ if (!name) return false;
59
+ if (/[\u0000-\u001f\u007f\ufffd]/.test(name)) return false;
60
+ return /[\p{L}\p{N}]/u.test(name);
61
+ }
62
+
63
+ /** 说过多少条 → 一个词。数字对"她记得这个人"没有帮助,只会挤掉具体的事。 */
64
+ function familiarityWord(count) {
65
+ const n = Number(count) || 0;
66
+ if (n >= 800) return '老熟人了';
67
+ if (n >= 200) return '聊得挺多';
68
+ if (n >= 50) return '聊过一阵';
69
+ if (n >= 10) return '说过几次话';
70
+ return '刚打过照面';
71
+ }
72
+
73
+ /** 秒级时间戳换算成毫秒,避免渲染成 1970。 */
74
+ function toMs(ts) {
75
+ const n = Number(ts);
76
+ if (!Number.isFinite(n) || n <= 0) return 0;
77
+ return n >= 1e11 ? n : n * 1000;
78
+ }
79
+
80
+ function fmtTime(ts) {
81
+ const n = toMs(ts);
82
+ if (!n) return '';
83
+ const d = new Date(n);
84
+ const pad = (x) => String(x).padStart(2, '0');
85
+ return `${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
86
+ }
87
+
88
+ function daysBetween(from, to) {
89
+ const a = toMs(from);
90
+ const b = toMs(to);
91
+ if (!a || !b) return null;
92
+ return Math.round((b - a) / 86400000);
93
+ }
94
+
95
+ /** 例句里不能出现会截断外层的引号;同时去掉换行。 */
96
+ function cleanSample(value) {
97
+ return String(value || '')
98
+ .replace(/[\u0000-\u001f\u007f]/g, ' ')
99
+ .replace(BIDI, '')
100
+ .replace(/\u2028|\u2029/g, ' ')
101
+ .replace(/[「」『』]/g, '') // 只去会截断外层的引号,正文标点保留
102
+ .replace(/\s+/g, ' ')
103
+ .trim();
104
+ }
105
+
106
+ /**
107
+ * 渲染一张人物卡。
108
+ * @param {object} card {名字, 消息条数, 首次出现(ts), 最后说话(ts), 常聊话题[], 关系阶段, 证据条数, 最近一句}
109
+ * @param {object} [options] {now, minEvidence}
110
+ * @returns {string} 一行文本;信息不足时返回空串
111
+ */
112
+ export function renderPersonCard(card, { now = Date.now(), minEvidence = 3 } = {}) {
113
+ if (!card) return '';
114
+ const name = baseName(card.名字);
115
+ if (!nameIsUsable(name)) return '';
116
+ const parts = [];
117
+
118
+ const since = daysBetween(card.首次出现, now);
119
+ if (since != null && since >= 0) parts.push(since <= 0 ? '刚认识' : `认识 ${since} 天`);
120
+ const count = Number(card.消息条数) || 0;
121
+ if (count > 0) parts.push(familiarityWord(count));
122
+ const last = humanTime(card.最后说话, { now });
123
+ if (last) parts.push(`最近 ${last}`);
124
+
125
+ const stage = String(card.关系阶段 || '').trim().replace(BIDI, '').replace(NAME_BREAKERS, '');
126
+ const evidence = Number(card.证据条数) || 0;
127
+ if (stage && stage !== '初识' && evidence >= minEvidence) parts.push(`关系:${stage}`);
128
+
129
+ // 话题只留中文的:英文串要么是用户名、要么是工具名,对"这人是谁"帮助不大。
130
+ const topics = (Array.isArray(card.常聊话题) ? card.常聊话题 : [])
131
+ .map((t) => String(t).replace(/\(\d+\)$/, '').trim().replace(BIDI, '').replace(NAME_BREAKERS, ''))
132
+ .filter((t) => /[\u3400-\u9fff]{2}/.test(t))
133
+ .slice(0, 3);
134
+ if (topics.length) parts.push(`常聊:${topics.join('、')}`);
135
+
136
+ // 引用/转发里的话可能是别人说的,归到她认识的人头上会张冠李戴:这种直接不用。
137
+ const rawSample = cleanSample(card.最近一句);
138
+ let sample = /^\[(?:引用|合并转发|转发|回复)/.test(rawSample) ? '' : rawSample;
139
+ sample = sample.slice(0, 28);
140
+ const tail = sample && sample !== '[图片]' && sample !== '[表情]' ? `。最近说过「${sample}」` : '';
141
+
142
+ if (!parts.length) return '';
143
+ return `你认识 ${name}:${parts.join(',')}${tail}。`;
144
+ }
145
+
146
+ /**
147
+ * 从一堆人里挑「当前说话的人」那张卡。
148
+ * - 同一 personId 可能有多个群的卡:先匹配 personId + 当前会话;私聊允许退回该人的任意一张
149
+ * - 默认**不按"话最多"退回别人**:群聊里那等于把别人的资料塞给在场的人
150
+ * @param {Array} cards 人物卡数组
151
+ * @param {{personId?: string, chatKey?: string}} speaker
152
+ * @param {{fallback?: boolean}} options fallback=true 才允许按话最多退回
153
+ */
154
+ export function pickPersonCard(cards, speaker = {}, { fallback = false } = {}) {
155
+ const list = Array.isArray(cards) ? cards : [];
156
+ const id = String(speaker.personId || '').trim();
157
+ const chat = String(speaker.chatKey || '').trim();
158
+ if (id) {
159
+ const samePerson = list.filter((c) => String(c.personId || '') === id);
160
+ if (!chat) {
161
+ // 没有会话键就无法确认是哪张卡;只有唯一一张时才用
162
+ return samePerson.length === 1 ? samePerson[0] : null;
163
+ }
164
+ const exact = samePerson.find((c) => String(c.chatKey || '') === chat);
165
+ if (exact) return exact;
166
+ if (/^(?:private)[_:-]/i.test(chat)) {
167
+ const anyChat = list.find((c) => String(c.personId || '') === id);
168
+ if (anyChat) return anyChat;
169
+ }
170
+ }
171
+ if (!fallback || id) return null;
172
+ if (chat) {
173
+ const inChat = list
174
+ .filter((c) => String(c.chatKey || '') === chat)
175
+ .sort((a, b) => (Number(b.消息条数) || 0) - (Number(a.消息条数) || 0));
176
+ if (inChat.length) return inChat[0];
177
+ }
178
+ return null;
179
+ }
@@ -0,0 +1,4 @@
1
+ /** 把「前几天 / 上周三 / 上个月 / 两周前 / 昨天晚上」翻成 [from, to);翻不出来返回 null */
2
+ export function parseRelativeWindow(text: string, options?: { now?: number }): { from: number; to: number; label: string; kind: string } | null
3
+ /** 时间是否落在窗口内;窗口为 null 时一律算在内 */
4
+ export function inWindow(ts: number | string | null | undefined, window: { from: number; to: number } | null): boolean
@@ -0,0 +1,123 @@
1
+ /**
2
+ * 把口语里的时间说法翻成时间窗口:「前几天」「上周三」「上个月」「昨天晚上」。
3
+ *
4
+ * 为什么要它:她问「前几天那个事」时,字面匹配找不到任何东西——那句话里没有具体日期。
5
+ * 先翻成 [from, to),再去检索,才可能命中。
6
+ *
7
+ * 纯函数,无 IO。拿不准就返回 null(宁可不过滤,也不乱过滤)。
8
+ */
9
+
10
+ const DAY = 86400000;
11
+
12
+ function toMs(ts) {
13
+ const n = Number(ts);
14
+ if (!Number.isFinite(n) || n <= 0) return 0;
15
+ return n >= 1e11 ? n : n * 1000;
16
+ }
17
+
18
+ function localDay(ms, offset = 0, hour = 0) {
19
+ const d = new Date(ms);
20
+ return new Date(d.getFullYear(), d.getMonth(), d.getDate() + offset, hour).getTime();
21
+ }
22
+
23
+ function startOfWeek(ms) {
24
+ const d = new Date(ms);
25
+ const offset = (d.getDay() + 6) % 7; // 周一为一周开始
26
+ return localDay(ms, -offset);
27
+ }
28
+
29
+ function startOfMonth(ms) {
30
+ const d = new Date(ms);
31
+ return new Date(d.getFullYear(), d.getMonth(), 1).getTime();
32
+ }
33
+
34
+ const CN_NUM = { 一: 1, 二: 2, 两: 2, 三: 3, 四: 4, 五: 5, 六: 6, 七: 7, 八: 8, 九: 9, 十: 10 };
35
+ function cnNumber(text) {
36
+ if (/^\d+$/.test(text)) return Number(text);
37
+ if (text === '十') return 10;
38
+ if (/^十[一二三四五六七八九]$/.test(text)) return 10 + CN_NUM[text[1]];
39
+ if (/^[一二两三四五六七八九]十$/.test(text)) return CN_NUM[text[0]] * 10;
40
+ if (/^[一二两三四五六七八九]十[一二三四五六七八九]$/.test(text)) return CN_NUM[text[0]] * 10 + CN_NUM[text[2]];
41
+ return CN_NUM[text] || 0;
42
+ }
43
+
44
+ /**
45
+ * 解析口语时间窗口。
46
+ * @param {string} text 她收到的那句话
47
+ * @param {object} [options] {now}
48
+ * @returns {{from:number,to:number,label:string,kind:string}|null}
49
+ */
50
+ export function parseRelativeWindow(text, { now = Date.now() } = {}) {
51
+ const q = String(text || '');
52
+ const n = toMs(now) || Date.now();
53
+ if (!q.trim()) return null;
54
+ const today = localDay(n);
55
+
56
+ // 数量要先于「前天」匹配,否则「三天前天气」会在量词边界处被截断。
57
+ const quantity = /([0-9]+|[一二两三四五六七八九十]+)\s*(天|日|个?周|个?星期|个?礼拜)(?:以|之)?前/.exec(q);
58
+ if (quantity) {
59
+ const k = cnNumber(quantity[1]);
60
+ const days = quantity[2] === '天' || quantity[2] === '日';
61
+ if (!k || k > (days ? 60 : 12)) return null;
62
+ const from = days ? localDay(today, -k) : localDay(startOfWeek(n), -7 * k);
63
+ return { from, to: localDay(from, days ? 1 : 7), label: days ? `${k} 天前` : `${k} 周前`, kind: days ? 'n-days' : 'n-weeks' };
64
+ }
65
+
66
+ if (/前几天|前两天|几天前|前些天|前阵子|这些天|这几天|这两天|近几天/.test(q)) {
67
+ return { from: localDay(today, -4), to: localDay(today, 1), label: '前几天', kind: 'fuzzy-days' };
68
+ }
69
+
70
+ const day = /(大前天|前天|昨天|今天|昨晚|今晚|今早)(?:的?\s*(上午|早上|中午|下午|傍晚|晚上|夜里|半夜))?/.exec(q);
71
+ if (day) {
72
+ const label = { 昨晚: '昨天', 今晚: '今天', 今早: '今天' }[day[1]] || day[1];
73
+ const offset = { 大前天: -3, 前天: -2, 昨天: -1, 今天: 0 }[label];
74
+ const base = localDay(today, offset);
75
+ const part = { 昨晚: '晚上', 今晚: '晚上', 今早: '早上' }[day[1]] || day[2];
76
+ if (!part) return { from: base, to: localDay(base, 1), label, kind: 'day' };
77
+ const [start, end] = { 上午: [6, 12], 早上: [6, 11], 中午: [11, 13], 下午: [13, 17], 傍晚: [17, 19], 晚上: [18, 22], 夜里: [22, 24], 半夜: [23, 26] }[part];
78
+ return { from: localDay(base, 0, start), to: localDay(base, 0, end), label: label + part, kind: 'part-of-day' };
79
+ }
80
+ if (/刚刚|刚才/.test(q)) {
81
+ return { from: n - 3600000, to: n + 60000, label: '刚刚', kind: 'recent' };
82
+ }
83
+
84
+ // 无「上/这/本」等限定词时,只有紧跟星期几才足以定位。
85
+ const week = /(?:(上上|下下|上|下|这|本)个?|(?<![每隔个0-9一二两三四五六七八九十])(?=(?:周|星期|礼拜)[一二三四五六日天]))(?:周|星期|礼拜)(?!末|年|围|堂|杰伦)([一二三四五六日天])?((?:以|之)前)?/.exec(q);
86
+ if (week) {
87
+ const which = week[1] || '这';
88
+ if (which.startsWith('下')) return null;
89
+ const shift = which === '上上' ? -14 : which === '上' ? -7 : 0;
90
+ const weekday = week[2];
91
+ const offset = weekday ? { 一: 0, 二: 1, 三: 2, 四: 3, 五: 4, 六: 5, 日: 6, 天: 6 }[weekday] : 0;
92
+ const from = localDay(startOfWeek(n), shift + offset);
93
+ const label = which + '周' + (weekday || '');
94
+ if (week[3]) return { from: 0, to: from, label: label + week[3], kind: 'older' };
95
+ return { from, to: localDay(from, weekday ? 1 : 7), label, kind: weekday ? 'weekday' : 'week' };
96
+ }
97
+
98
+ const month = /(上上|上|这|本)个?月(?!亮|光|饼|份)((?:以|之)前)?/.exec(q);
99
+ if (month) {
100
+ const d = new Date(n);
101
+ const shift = month[1] === '上上' ? -2 : month[1] === '上' ? -1 : 0;
102
+ const from = new Date(d.getFullYear(), d.getMonth() + shift, 1).getTime();
103
+ const label = month[1] + '个月';
104
+ if (month[2]) return { from: 0, to: from, label: label + month[2], kind: 'older' };
105
+ return { from, to: new Date(d.getFullYear(), d.getMonth() + shift + 1, 1).getTime(), label, kind: 'month' };
106
+ }
107
+
108
+ if (/最近|近期/.test(q)) {
109
+ return { from: localDay(today, -3), to: localDay(today, 1), label: '最近', kind: 'recent' };
110
+ }
111
+ if (/更早/.test(q)) {
112
+ return { from: startOfMonth(n) - 90 * DAY, to: startOfMonth(n), label: '上个月以前', kind: 'older' };
113
+ }
114
+ return null;
115
+ }
116
+
117
+ /** 是否落在窗口里。窗口为 null 时一律算在内(不过滤)。 */
118
+ export function inWindow(ts, window) {
119
+ if (!window) return true;
120
+ const t = toMs(ts);
121
+ if (!t) return false;
122
+ return t >= window.from && t < window.to;
123
+ }
@@ -0,0 +1,10 @@
1
+ /** 去掉人设后缀(#p_xxx),得到会话级键 */
2
+ export function baseChatKey(chatKey: string): string
3
+ /** 这个键是不是人设级 */
4
+ export function isPersonaScoped(chatKey: string): boolean
5
+ /** 一次查询应覆盖的键:人设级 = [人设键, 会话键];会话级 = [会话键](不反向并入,避免串台) */
6
+ export function scopeKeysFor(chatKey: string): string[]
7
+ /** 记录是否落在查询范围内 */
8
+ export function recordInScope(recordChatKey: string, queryChatKey: string): boolean
9
+ /** 一个键的所有写法(去重) */
10
+ export function variantsOf(chatKey: string): string[]
@@ -0,0 +1,56 @@
1
+ /**
2
+ * 会话作用域键:同一个会话可能有两种写法——会话级 `group_123` 和人设级 `group_123#p_abcd`。
3
+ * 检索时如果只认精确键,人设级查询就看不到会话级的老记录。
4
+ *
5
+ * 规则(从 QQ Agent 插件的真实 bug 里提炼):
6
+ * - 人设级查询 = 人设级记录 + 同会话的会话级记录
7
+ * - 会话级查询 = 只认会话级记录(不反向并入人设记录,避免把某人的记忆串给所有人)
8
+ *
9
+ * 纯函数,宿主无关。
10
+ */
11
+
12
+ const PERSONA_SUFFIX = /#p_[A-Za-z0-9]+$/i;
13
+
14
+ /** 去掉人设后缀,得到会话级键。 */
15
+ export function baseChatKey(chatKey) {
16
+ return String(chatKey || '').trim().replace(PERSONA_SUFFIX, '');
17
+ }
18
+
19
+ /** 这个键是不是人设级。 */
20
+ export function isPersonaScoped(chatKey) {
21
+ return PERSONA_SUFFIX.test(String(chatKey || '').trim());
22
+ }
23
+
24
+ /**
25
+ * 一次查询应该覆盖哪些键。
26
+ * @param {string} chatKey 当前会话键
27
+ * @returns {string[]} 由具体到宽泛;会话级查询只有一个
28
+ */
29
+ export function scopeKeysFor(chatKey) {
30
+ const raw = String(chatKey || '').trim();
31
+ if (!raw) return [];
32
+ const base = baseChatKey(raw);
33
+ if (!base || base === raw) return [raw];
34
+ return [raw, base];
35
+ }
36
+
37
+ /**
38
+ * 一条记录的会话键是否落在本次查询范围内。
39
+ * @param {string} recordChatKey 记录自己的键
40
+ * @param {string} queryChatKey 查询用的键
41
+ */
42
+ export function recordInScope(recordChatKey, queryChatKey) {
43
+ const record = String(recordChatKey || '').trim();
44
+ const query = String(queryChatKey || '').trim();
45
+ if (!query) return true; // 不限定会话 = 全局
46
+ if (!record) return false;
47
+ return scopeKeysFor(query).includes(record);
48
+ }
49
+
50
+ /** 供测试与迁移用:把一个键的两种写法都列出来。 */
51
+ export function variantsOf(chatKey) {
52
+ const raw = String(chatKey || '').trim();
53
+ const base = baseChatKey(raw);
54
+ if (!base) return [];
55
+ return [...new Set([base, raw])];
56
+ }
@@ -0,0 +1,6 @@
1
+ /** 「刚刚 / 12 分钟前 / 今天 09:12 / 昨天 20:30 / 3 天前 / 上周三 / 2 个月前 / 2025-08-01」 */
2
+ export function humanTime(ts: number | string | null | undefined, options?: { now?: number }): string
3
+ /** 只要时长,不要时刻:「刚刚 / 12 分钟前 / 3 小时前 / 昨天 / 4 天前」 */
4
+ export function timeAgo(ts: number | string | null | undefined, options?: { now?: number }): string
5
+ /** 本地日历日差:0=今天,1=昨天,2=前天 */
6
+ export function dayDiff(ts: number, now?: number): number | null
@@ -0,0 +1,89 @@
1
+ /**
2
+ * 人话时间:把时间戳说成她该听见的样子——「昨天 20:30」「上周三」「3 天前」,而不是「11-20 20:30」。
3
+ *
4
+ * 为什么要单独一层:她答「前几天那个事」时,需要的是「这属于哪一天」,而不是一个日期字符串。
5
+ * 纯函数,无 IO。
6
+ */
7
+
8
+ function toMs(ts) {
9
+ const n = Number(ts);
10
+ if (!Number.isFinite(n) || n <= 0) return 0;
11
+ return n >= 1e11 ? n : n * 1000; // 秒 → 毫秒
12
+ }
13
+
14
+ function pad(n) {
15
+ return String(n).padStart(2, '0');
16
+ }
17
+
18
+ function clock(d) {
19
+ return `${pad(d.getHours())}:${pad(d.getMinutes())}`;
20
+ }
21
+
22
+ /** 本地日历日差:0=今天,1=昨天,2=前天…… */
23
+ export function dayDiff(ts, now = Date.now()) {
24
+ const a = toMs(ts);
25
+ const b = toMs(now);
26
+ if (!a || !b) return null;
27
+ const da = new Date(a);
28
+ const db = new Date(b);
29
+ const startA = new Date(da.getFullYear(), da.getMonth(), da.getDate()).getTime();
30
+ const startB = new Date(db.getFullYear(), db.getMonth(), db.getDate()).getTime();
31
+ return Math.round((startB - startA) / 86400000);
32
+ }
33
+
34
+ const WEEK = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
35
+
36
+ /**
37
+ * 「人话」时间。
38
+ * @param {number} ts 时间戳(秒或毫秒)
39
+ * @param {object} [options] {now}
40
+ * @returns {string} 例:刚刚 / 12 分钟前 / 今天 09:12 / 昨天 20:30 / 前天 18:40 / 3 天前 / 上周三 / 3 周前 / 2 个月前 / 2025-08-01
41
+ */
42
+ export function humanTime(ts, { now = Date.now() } = {}) {
43
+ const t = toMs(ts);
44
+ const n = toMs(now) || Date.now();
45
+ if (!t) return '';
46
+ const diff = n - t;
47
+ if (diff < 0) return clock(new Date(t)); // 未来的时间:只给时刻,不编「之后」
48
+ const minutes = diff / 60000;
49
+ if (minutes < 1) return '刚刚';
50
+ if (minutes < 60) return `${Math.floor(minutes)} 分钟前`;
51
+
52
+ const days = dayDiff(t, n);
53
+ const d = new Date(t);
54
+ if (days === 0) return `今天 ${clock(d)}`;
55
+ if (days === 1) return `昨天 ${clock(d)}`;
56
+ if (days === 2) return `前天 ${clock(d)}`;
57
+ if (days != null && days >= 3 && days <= 6) return `${days} 天前`;
58
+ const current = new Date(n);
59
+ if (days >= 7 && days <= 13) {
60
+ const daysSinceMonday = (current.getDay() + 6) % 7;
61
+ return days <= daysSinceMonday + 7 ? '上' + WEEK[d.getDay()] : `${days} 天前`;
62
+ }
63
+ if (days != null && days >= 14 && days <= 29) return `${Math.round(days / 7)} 周前`;
64
+ if (days != null && days >= 30 && days <= 364) {
65
+ const months = (current.getFullYear() - d.getFullYear()) * 12 + current.getMonth() - d.getMonth();
66
+ if (months === 0) return `${Math.round(days / 7)} 周前`;
67
+ return months === 1 ? '上个月' : `${months} 个月前`;
68
+ }
69
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
70
+ }
71
+
72
+ /** 「多久以前」的短说法:刚刚 / 12 分钟前 / 3 小时前 / 昨天 / 4 天前 / 2 个月前 */
73
+ export function timeAgo(ts, { now = Date.now() } = {}) {
74
+ const t = toMs(ts);
75
+ const n = toMs(now) || Date.now();
76
+ if (!t) return '';
77
+ const diff = Math.max(0, n - t);
78
+ const minutes = diff / 60000;
79
+ if (minutes < 1) return '刚刚';
80
+ if (minutes < 60) return `${Math.floor(minutes)} 分钟前`;
81
+ const hours = minutes / 60;
82
+ if (hours < 24 && dayDiff(t, n) === 0) return `${Math.floor(hours)} 小时前`;
83
+ const days = dayDiff(t, n);
84
+ if (days === 1) return '昨天';
85
+ if (days === 2) return '前天';
86
+ if (days != null && days < 30) return `${days} 天前`;
87
+ if (days != null && days < 365) return `${Math.max(1, Math.round(days / 30))} 个月前`;
88
+ return '很久以前';
89
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "whale-memory-core",
3
- "version": "0.18.2",
3
+ "version": "0.19.2",
4
4
  "description": "Self-layer autobiographical memory core: then / later, append-only. Vault, evidence and consolidation live in the QQ Agent plugin.",
5
5
  "type": "module",
6
6
  "main": "./index.js",
@@ -92,6 +92,18 @@
92
92
  "./timeline-query": {
93
93
  "types": "./lib/fact-timeline-query.d.ts",
94
94
  "default": "./lib/fact-timeline-query.js"
95
+ },
96
+ "./time-sense": {
97
+ "types": "./lib/time-sense.d.ts",
98
+ "default": "./lib/time-sense.js"
99
+ },
100
+ "./relative-window": {
101
+ "types": "./lib/relative-window.d.ts",
102
+ "default": "./lib/relative-window.js"
103
+ },
104
+ "./person-card": {
105
+ "types": "./lib/person-card.d.ts",
106
+ "default": "./lib/person-card.js"
95
107
  }
96
108
  },
97
109
  "files": [