dsh-self-clock 0.0.0-stage → 0.3.9

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/lib/core.js ADDED
@@ -0,0 +1,318 @@
1
+ /**
2
+ * 纯逻辑:什么时候该响、时段怎么顺延、每日预算怎么算、cron 怎么解、状态怎么描述。
3
+ * 这里不碰 ctx、不碰文件,方便直接拿 node 跑测试。
4
+ */
5
+
6
+ export const MINUTE = 60_000
7
+ export const DAY = 86_400_000
8
+
9
+ /** "08:30" → 510(当天的分钟数);写错就当没设 */
10
+ export function parseHHMM(value) {
11
+ const m = /^(\d{1,2}):(\d{2})$/.exec(String(value ?? '').trim())
12
+ if (!m) return null
13
+ const h = Number(m[1])
14
+ const mi = Number(m[2])
15
+ if (h > 23 || mi > 59) return null
16
+ return h * 60 + mi
17
+ }
18
+
19
+ /** 本地的「当天第几分钟」 */
20
+ export function minuteOfDay(ms) {
21
+ const d = new Date(ms)
22
+ return d.getHours() * 60 + d.getMinutes()
23
+ }
24
+
25
+ /** 本地某天的 00:00(毫秒) */
26
+ export function startOfDay(ms) {
27
+ const d = new Date(ms)
28
+ d.setHours(0, 0, 0, 0)
29
+ return d.getTime()
30
+ }
31
+
32
+ /** 本地日期键 2026-11-22 */
33
+ export function dayKey(ms) {
34
+ const d = new Date(ms)
35
+ const p = (n) => String(n).padStart(2, '0')
36
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`
37
+ }
38
+
39
+ /** 本地 HH:MM */
40
+ export function hhmm(ms) {
41
+ const d = new Date(ms)
42
+ const p = (n) => String(n).padStart(2, '0')
43
+ return `${p(d.getHours())}:${p(d.getMinutes())}`
44
+ }
45
+
46
+ const pad2 = (n) => String(n).padStart(2, '0')
47
+
48
+ /**
49
+ * 旧的安静时段写法(全局 quietStart/quietEnd)。现在主用 alarm.windowStart/windowEnd,
50
+ * 这两个留作兼容:老数据、老测试、配置里没迁完的部分还认它。
51
+ */
52
+ export function quietRange(cfg = {}) {
53
+ const start = parseHHMM(cfg.quietStart)
54
+ const end = parseHHMM(cfg.quietEnd)
55
+ if (start === null || end === null || start === end) return null
56
+ return { start, end }
57
+ }
58
+
59
+ export function isQuiet(ms, cfg = {}) {
60
+ const range = quietRange(cfg)
61
+ if (!range) return false
62
+ const m = minuteOfDay(ms)
63
+ return range.start < range.end
64
+ ? m >= range.start && m < range.end
65
+ : m >= range.start || m < range.end
66
+ }
67
+
68
+ /** 从 ms 起,第一个不在安静时段里的时刻(ms 本身不安静就原样返回) */
69
+ export function exitQuiet(ms, cfg = {}) {
70
+ const range = quietRange(cfg)
71
+ if (!range || !isQuiet(ms, cfg)) return ms
72
+ const base = startOfDay(ms)
73
+ const todayEnd = base + range.end * MINUTE
74
+ if (range.start < range.end) return todayEnd > ms ? todayEnd : todayEnd + DAY
75
+ return todayEnd > ms ? todayEnd : todayEnd + DAY
76
+ }
77
+
78
+ /* ---------------------------------------------------------------- cron */
79
+
80
+ const FIELDS = [
81
+ { name: 'minute', min: 0, max: 59 },
82
+ { name: 'hour', min: 0, max: 23 },
83
+ { name: 'dayOfMonth', min: 1, max: 31 },
84
+ { name: 'month', min: 1, max: 12 },
85
+ { name: 'dayOfWeek', min: 0, max: 6 },
86
+ ]
87
+
88
+ /** 一个字段 → 允许值集合;支持 *、a、a,b、a-b、*\/n、a-b\/n */
89
+ function parseField(text, { min, max }) {
90
+ const out = new Set()
91
+ for (const part of String(text).split(',')) {
92
+ const [body, stepText] = part.split('/')
93
+ const step = stepText === undefined ? 1 : Number(stepText)
94
+ if (!Number.isInteger(step) || step < 1) throw new Error(`cron 步长不合法:${part}`)
95
+ let lo = min
96
+ let hi = max
97
+ if (body !== '*') {
98
+ const m = /^(\d+)(?:-(\d+))?$/.exec(body)
99
+ if (!m) throw new Error(`cron 字段不合法:${part}`)
100
+ lo = Number(m[1])
101
+ hi = m[2] === undefined ? (stepText === undefined ? Number(m[1]) : max) : Number(m[2])
102
+ if (lo < min || hi > max || lo > hi) throw new Error(`cron 字段超范围:${part}`)
103
+ }
104
+ for (let v = lo; v <= hi; v += step) out.add(v)
105
+ }
106
+ if (out.size === 0) throw new Error('cron 字段是空的')
107
+ return out
108
+ }
109
+
110
+ /** "30 7 * * *" → 五个集合 */
111
+ export function parseCron(expr) {
112
+ const parts = String(expr ?? '').trim().split(/\s+/)
113
+ if (parts.length !== 5) throw new Error('cron 要五个字段:分 时 日 月 周')
114
+ const sets = parts.map((p, i) => parseField(p, FIELDS[i]))
115
+ return {
116
+ minute: sets[0],
117
+ hour: sets[1],
118
+ dayOfMonth: sets[2],
119
+ month: sets[3],
120
+ dayOfWeek: sets[4],
121
+ expr: parts.join(' '),
122
+ }
123
+ }
124
+
125
+ function cronMatches(parsed, date) {
126
+ if (!parsed.minute.has(date.getMinutes())) return false
127
+ if (!parsed.hour.has(date.getHours())) return false
128
+ if (!parsed.month.has(date.getMonth() + 1)) return false
129
+ const domOk = parsed.dayOfMonth.has(date.getDate())
130
+ const dowOk = parsed.dayOfWeek.has(date.getDay())
131
+ // 日和周都限定时,按 cron 惯例取「或」
132
+ const domRestricted = parsed.dayOfMonth.size !== 31
133
+ const dowRestricted = parsed.dayOfWeek.size !== 7
134
+ if (domRestricted && dowRestricted) return domOk || dowOk
135
+ return domOk && dowOk
136
+ }
137
+
138
+ /**
139
+ * 严格晚于 fromMs 的下一个 cron 时刻;一年内没有就返回 null。
140
+ * 从下一分钟开始扫,整点省略的字段也能接受。
141
+ */
142
+ export function cronNext(parsed, fromMs) {
143
+ const start = Math.floor(fromMs / MINUTE) * MINUTE + MINUTE
144
+ const limit = start + 370 * DAY
145
+ for (let t = start; t <= limit; t += MINUTE) {
146
+ if (cronMatches(parsed, new Date(t))) return t
147
+ }
148
+ return null
149
+ }
150
+
151
+ /**
152
+ * 读 alarm.cronParsed:落盘回来可能是空对象(Set 序列化后变 {}),
153
+ * 这时候用 expr 重新解析——不能让「空集合算出 null 就静默不动」再发生。
154
+ */
155
+ export function cronParsedOf(alarm) {
156
+ const parsed = alarm?.cronParsed
157
+ if (parsed && typeof parsed === 'object') {
158
+ const built = {}
159
+ let ok = true
160
+ for (const field of FIELDS) {
161
+ const value = parsed[field.name]
162
+ let set = null
163
+ if (value instanceof Set) set = value
164
+ else if (Array.isArray(value)) set = new Set(value.filter((v) => Number.isInteger(v)))
165
+ if (!set || set.size === 0) { ok = false; break }
166
+ built[field.name] = set
167
+ }
168
+ if (ok) return { parsed: { ...built, expr: parsed.expr || alarm?.cron || '' }, error: null }
169
+ }
170
+ try {
171
+ return { parsed: parseCron(alarm?.cron), error: null }
172
+ } catch (error) {
173
+ return { parsed: null, error: String(error?.message || error) }
174
+ }
175
+ }
176
+
177
+ /* ------------------------------------------------------------ 下一次 */
178
+
179
+ /**
180
+ * 时段(小时制):alarm.windowStart/windowEnd 优先,其次旧的 quietStart/quietEnd。
181
+ * start=0 且 end=23/24 当全天;start > end 表示跨夜。
182
+ */
183
+ export function windowOf(alarm = {}) {
184
+ const s = Number.isInteger(alarm.windowStart) ? alarm.windowStart * 60 : 0
185
+ const e = Number.isInteger(alarm.windowEnd) ? alarm.windowEnd * 60 : 24 * 60
186
+ if (s === e) return null
187
+ if (s === 0 && (e === 23 * 60 || e === 24 * 60)) return null
188
+ return { start: s, end: e }
189
+ }
190
+
191
+ export function isInWindow(ms, alarm = {}) {
192
+ const range = windowOf(alarm)
193
+ if (!range) return true
194
+ const m = minuteOfDay(ms)
195
+ return range.start < range.end
196
+ ? m >= range.start && m < range.end
197
+ : m >= range.start || m < range.end
198
+ }
199
+
200
+ /** 不在时段里时,下一个「时段开始」的时刻 */
201
+ export function exitWindow(ms, alarm = {}) {
202
+ const range = windowOf(alarm)
203
+ if (!range || isInWindow(ms, alarm)) return ms
204
+ const base = startOfDay(ms)
205
+ const todayStart = base + range.start * MINUTE
206
+ return todayStart > ms ? todayStart : todayStart + DAY
207
+ }
208
+
209
+ /** 面板/工具都要能回答「为什么没响」 */
210
+ export function statusOf(alarm = {}, now = Date.now(), extra = {}) {
211
+ if (alarm.enabled === false) return { code: 'disabled', text: '已关闭(总开关)' }
212
+
213
+ const mutedUntil = alarm.mutedUntil ? Date.parse(alarm.mutedUntil) : NaN
214
+ if (Number.isFinite(mutedUntil) && mutedUntil > now) {
215
+ return { code: 'muted', text: `临时静音中 · ${hhmm(mutedUntil)} 恢复`, until: mutedUntil }
216
+ }
217
+
218
+ const used = Number(extra.used ?? 0)
219
+ const budget = Number(extra.budget ?? alarm.dailyBudget ?? 48)
220
+ if (used >= budget) return { code: 'budget', text: `今日预算用完(${used}/${budget})` }
221
+
222
+ if (!isInWindow(now, alarm)) {
223
+ const range = windowOf(alarm)
224
+ const s = Math.floor(range.start / 60)
225
+ const e = Math.floor(range.end / 60)
226
+ const cross = s > e ? ',跨夜' : ''
227
+ return { code: 'window', text: `不在时段(${pad2(s)}:00–${pad2(e)}:00${cross})` }
228
+ }
229
+
230
+ if (!Number.isFinite(alarm.nextAt)) return { code: 'none', text: '⚠ 未排到下次触发' }
231
+ return { code: 'waiting', text: `等待中 · 下次 ${hhmm(alarm.nextAt)}` }
232
+ }
233
+
234
+ /** 不考虑时段时,闹钟的原始下一次 */
235
+ function rawNext(alarm, fromMs) {
236
+ if (alarm.mode === 'once') return alarm.at ?? null
237
+ if (alarm.mode === 'every' || alarm.mode === 'interval') {
238
+ const step = Number(alarm.everyMinutes) * MINUTE
239
+ if (!Number.isFinite(step) || step <= 0) return null
240
+ const base = alarm.baseAt ?? alarm.createdAt ?? fromMs
241
+ // 刚响过就从前一次之后算,避免同一刻反复响;停机错过的那几拍直接跳到下一个未过的时刻
242
+ const from = Math.max(fromMs, (alarm.lastFiredAt ?? 0) + 1)
243
+ const k = Math.max(1, Math.ceil((from - base) / step))
244
+ return base + k * step
245
+ }
246
+ if (alarm.mode === 'cron') {
247
+ const { parsed } = cronParsedOf(alarm)
248
+ if (!parsed) return null
249
+ return cronNext(parsed, fromMs)
250
+ }
251
+ return null
252
+ }
253
+
254
+ /** 闹钟的下一次响铃时刻:raw 落在时段外就顺延到时段里(不报错、不丢)。一次性闹钟顺延后仍只响一次。 */
255
+ export function nextFire(alarm, fromMs, cfg = {}) {
256
+ let t = rawNext(alarm, fromMs)
257
+ if (t === null || t === undefined) return null
258
+ if (isInWindow(t, alarm)) return t
259
+
260
+ const leave = exitWindow(t, alarm)
261
+ if (alarm.mode === 'once') return leave
262
+
263
+ if (alarm.mode === 'cron') {
264
+ const { parsed } = cronParsedOf(alarm)
265
+ if (!parsed) return leave
266
+ let n = cronNext(parsed, leave - MINUTE)
267
+ let guard = 0
268
+ while (n !== null && !isInWindow(n, alarm) && guard++ < 64) {
269
+ n = cronNext(parsed, exitWindow(n, alarm) - MINUTE)
270
+ }
271
+ return n
272
+ }
273
+
274
+ // every/interval:按 base 的整倍数往后挪,直到进入时段
275
+ const step = Number(alarm.everyMinutes) * MINUTE
276
+ const base = alarm.baseAt ?? alarm.createdAt ?? fromMs
277
+ const k = Math.max(1, Math.ceil((leave - base) / step))
278
+ let cur = base + k * step
279
+ let guard = 0
280
+ while (!isInWindow(cur, alarm) && guard++ < 64) cur += step
281
+ return cur
282
+ }
283
+
284
+ /**
285
+ * 「现在算不算我自己的时间」——纯判断,不读文件:
286
+ * ① 距上条 user < chatGrace → 跳过 ② 还没回他 → 跳过 ③ 最后一条 assistant 距今 < postReplyGrace → 跳过
287
+ * ④ 5–20 分钟 → 温和版 ⑤ >20 分钟 → 原文
288
+ */
289
+ export function judgeTiming(input = {}) {
290
+ const now = Number(input.now ?? Date.now())
291
+ const userAt = Number.isFinite(input.userAt) ? input.userAt : null
292
+ const lastAssistantAt = Number.isFinite(input.lastAssistantAt) ? input.lastAssistantAt : null
293
+ const chatGrace = Number(input.chatGraceMinutes ?? 5)
294
+ const postGrace = Number(input.postReplyGraceMinutes ?? 2)
295
+
296
+ if (userAt === null) return { kind: 'deliver', mode: 'normal', note: '会话里还没有他的消息' }
297
+
298
+ const gap = (now - userAt) / MINUTE
299
+ if (gap < chatGrace) return { kind: 'skip', reason: `距上条消息 ${Math.round(gap)} 分钟`, note: '太近' }
300
+ if (lastAssistantAt === null || lastAssistantAt < userAt) {
301
+ return { kind: 'skip', reason: '他在等回复', note: '上一条还没回' }
302
+ }
303
+ if ((now - lastAssistantAt) / MINUTE < postGrace) return { kind: 'skip', reason: '刚收尾', note: '最后一句是刚说的' }
304
+ if (gap <= 20) return { kind: 'deliver', mode: 'gentle', note: `距上条消息 ${Math.round(gap)} 分钟` }
305
+ return { kind: 'deliver', mode: 'normal', note: `距上条消息 ${Math.round(gap)} 分钟` }
306
+ }
307
+
308
+ /** 当天的预算状态;跨天就重置 */
309
+ export function budgetState(usage, nowMs) {
310
+ const today = dayKey(nowMs)
311
+ const used = usage && usage.date === today ? Number(usage.count) || 0 : 0
312
+ return { date: today, used }
313
+ }
314
+
315
+ export function budgetLeft(usage, nowMs, limit) {
316
+ const { used } = budgetState(usage, nowMs)
317
+ return Math.max(0, Number(limit) - used)
318
+ }
package/lib/message.js ADDED
@@ -0,0 +1,95 @@
1
+ /**
2
+ * 造一条「notice 型」用户消息:角色是 user,来源写成 heartbeat + form:notice,
3
+ * 这样界面按系统提示那一排显示,不会冒充杨欣荣在说话。
4
+ *
5
+ * 优先从宿主那棵树里取官方的 createUserMessage(拿不到就手工造一个等价对象)。
6
+ * 桌面版 profile 用 autoInstallPeers:false,裸 import 常常解析不到——
7
+ * 所以这里「能拿到就用官方的,拿不到退到等价实现」,绝不因为一个 import 让整条插件不激活。
8
+ */
9
+ import { randomUUID } from 'node:crypto';
10
+ import { existsSync } from 'node:fs';
11
+ import { join } from 'node:path';
12
+ import { homedir } from 'node:os';
13
+ import { pathToFileURL } from 'node:url';
14
+
15
+ const PKG = 'dsh-llm';
16
+ const LOADED = Symbol('heartbeat.createUserMessage');
17
+
18
+ function candidateFiles() {
19
+ const out = [];
20
+ const add = (p) => {
21
+ if (p && existsSync(p) && !out.includes(p)) out.push(p);
22
+ };
23
+ const res = process.resourcesPath;
24
+ if (res) {
25
+ add(join(res, 'app.asar', 'dsh', 'node_modules', '@deepseek-ai', PKG, 'lib', 'index.js'));
26
+ add(join(res, 'app', 'dsh', 'node_modules', '@deepseek-ai', PKG, 'lib', 'index.js'));
27
+ }
28
+ const appdata = process.env.APPDATA;
29
+ if (appdata) {
30
+ add(join(appdata, 'npm', 'node_modules', '@deepseek-ai', 'dsh', 'node_modules', '@deepseek-ai', PKG, 'lib', 'index.js'));
31
+ }
32
+ const dshHome = process.env.DSH_HOME || join(homedir(), '.dsh');
33
+ try {
34
+ for (const profile of ['desktop', 'web']) {
35
+ add(join(dshHome, 'profiles', profile, 'node_modules', '@deepseek-ai', PKG, 'lib', 'index.js'));
36
+ }
37
+ } catch {
38
+ /* 没有就算了 */
39
+ }
40
+ return out;
41
+ }
42
+
43
+ function fallback(input) {
44
+ const text = typeof input?.text === 'string'
45
+ ? input.text
46
+ : (Array.isArray(input?.content) ? input.content : [])
47
+ .filter((block) => block?.type === 'text')
48
+ .map((block) => String(block.text ?? ''))
49
+ .join('')
50
+ const message = {
51
+ id: randomUUID(),
52
+ role: 'user',
53
+ content: [{ type: 'text', text }],
54
+ source: { kind: 'heartbeat', form: 'notice', summary: input.summary ?? text.slice(0, 120) },
55
+ };
56
+ return Object.freeze({
57
+ ...message,
58
+ content: Object.freeze(message.content),
59
+ source: Object.freeze(message.source),
60
+ });
61
+ }
62
+
63
+ let cached;
64
+
65
+ /** 取 createUserMessage(缓存;拿不到官方实现就用本地等价实现) */
66
+ export async function loadCreateUserMessage(onNote = () => {}) {
67
+ if (cached) return cached;
68
+ for (const file of candidateFiles()) {
69
+ try {
70
+ const mod = await import(pathToFileURL(file).href);
71
+ if (typeof mod.createUserMessage === 'function') {
72
+ cached = mod.createUserMessage;
73
+ onNote(`createUserMessage:用宿主那份(${file})`);
74
+ return cached;
75
+ }
76
+ } catch (error) {
77
+ onNote(`createUserMessage:${file} 取不到(${error?.code || error?.message || error})`);
78
+ }
79
+ }
80
+ try {
81
+ const mod = await import('@deepseek-ai/dsh-llm');
82
+ if (typeof mod?.createUserMessage === 'function') {
83
+ cached = mod.createUserMessage;
84
+ onNote('createUserMessage:用裸 import 那份');
85
+ return cached;
86
+ }
87
+ } catch {
88
+ /* 走兜底 */
89
+ }
90
+ cached = fallback;
91
+ onNote('createUserMessage:官方那份拿不到,用本地等价实现(结构一致)');
92
+ return cached;
93
+ }
94
+
95
+ export { LOADED };
@@ -0,0 +1,236 @@
1
+ /**
2
+ * presence —— 从会话日志正文里认「他本人最后说的一句话」。
3
+ *
4
+ * 为什么不看 mtime:会话日志每轮都在写(系统注入、汇报都算),mtime 永远是新的。
5
+ * 只有正文能告诉你是谁在写。
6
+ *
7
+ * 判据是三道闸(顺序不能换):
8
+ * ① kind 白名单 —— 只认这些来源(user / qq / 桥自定义 kind)
9
+ * ② 必须含 —— 正则,给「接口收不了 source、只能往正文里盖章」的桥用
10
+ * ③ 排除 —— 正则数组,命中就不算他说的(系统注入、定时、插件汇报)
11
+ *
12
+ * 麻烦的地方在于:真正被写进 session.v4 的 `user/message` 事件里**不带 source**。
13
+ * 来源只活在 `agent/inbox/spliced` 事件的 inserted[].source 里。所以先把 spliced
14
+ * 建一张「正文 → source」的表,再拿 user/message 的正文去对。对不上就当 'user'。
15
+ */
16
+ import { readdir, readFile } from 'node:fs/promises'
17
+ import { join } from 'node:path'
18
+ import { zstdDecompressSync } from 'node:zlib'
19
+
20
+ const FRAME = [0x28, 0xb5, 0x2f, 0xfd]
21
+ const PREVIEW = 80
22
+ const SPLICE_KEY = 200
23
+
24
+ /** 多帧 zstd:按魔数切开逐帧解,再拼起来。只解第一帧会漏掉 99% 的内容。 */
25
+ export function decodeLog(buffer, options = {}) {
26
+ const frames = []
27
+ let start = -1
28
+ for (let i = 0; i + 3 < buffer.length; i += 1) {
29
+ if (buffer[i] === FRAME[0] && buffer[i + 1] === FRAME[1] && buffer[i + 2] === FRAME[2] && buffer[i + 3] === FRAME[3]) {
30
+ if (start >= 0) frames.push(buffer.subarray(start, i))
31
+ start = i
32
+ }
33
+ }
34
+ if (start >= 0) frames.push(buffer.subarray(start))
35
+ if (frames.length === 0) return ''
36
+ const limit = Number.isInteger(options.maxFrames) && options.maxFrames > 0 ? options.maxFrames : frames.length
37
+ const parts = []
38
+ for (const frame of frames.slice(-limit)) {
39
+ try {
40
+ parts.push(zstdDecompressSync(frame).toString('utf8'))
41
+ } catch {
42
+ // 坏帧跳过,别整份报废
43
+ }
44
+ }
45
+ return parts.join('')
46
+ }
47
+
48
+ export function parseEvents(text) {
49
+ const out = []
50
+ for (const line of text.split('\n')) {
51
+ if (!line.trim()) continue
52
+ try {
53
+ const event = JSON.parse(line)
54
+ if (event && typeof event === 'object') out.push(event)
55
+ } catch {
56
+ // 半行/坏行跳过
57
+ }
58
+ }
59
+ return out
60
+ }
61
+
62
+ /** content 可能是字符串、数组或分片,统一拼成正文。 */
63
+ export function textOfContent(content) {
64
+ if (typeof content === 'string') return content
65
+ if (!Array.isArray(content)) return ''
66
+ const parts = []
67
+ for (const part of content) {
68
+ if (typeof part === 'string') parts.push(part)
69
+ else if (part && typeof part.text === 'string') parts.push(part.text)
70
+ }
71
+ return parts.join('')
72
+ }
73
+
74
+ function spliceKey(text) {
75
+ return text.trim().slice(0, SPLICE_KEY)
76
+ }
77
+
78
+ /** 把 agent/inbox/spliced 里的 source 记成「正文 → 来源」,给不带 source 的 user/message 用。 */
79
+ export function buildSpliceIndex(events) {
80
+ const index = new Map()
81
+ for (const event of events) {
82
+ if (event.type !== 'agent/inbox/spliced') continue
83
+ const inserted = event.data?.inserted
84
+ if (!Array.isArray(inserted)) continue
85
+ for (const item of inserted) {
86
+ const text = textOfContent(item?.content)
87
+ if (!text.trim()) continue
88
+ const key = spliceKey(text)
89
+ if (index.has(key)) continue
90
+ const source = item?.source ?? {}
91
+ index.set(key, {
92
+ kind: typeof source.kind === 'string' && source.kind ? source.kind : 'user',
93
+ form: typeof source.form === 'string' ? source.form : null,
94
+ })
95
+ }
96
+ }
97
+ return index
98
+ }
99
+
100
+ export function channelOf(source) {
101
+ const kind = typeof source?.kind === 'string' && source.kind ? source.kind : 'unknown'
102
+ const form = typeof source?.form === 'string' && source.form ? `/${source.form}` : ''
103
+ return `${kind}${form}`
104
+ }
105
+
106
+ /** 三道闸:kind 白名单 → 必须含 → 排除。返回 { ok, kind, reason }。 */
107
+ export function judge(text, kind, cfg) {
108
+ const kinds = Array.isArray(cfg?.ownerSourceKinds) ? cfg.ownerSourceKinds : []
109
+ if (kinds.length > 0 && !kinds.includes(kind)) return { ok: false, reason: 'kind' }
110
+
111
+ const require = typeof cfg?.ownerSourceRequire === 'string' ? cfg.ownerSourceRequire.trim() : ''
112
+ if (require) {
113
+ let re
114
+ try {
115
+ re = new RegExp(require, 'u')
116
+ } catch {
117
+ re = null
118
+ }
119
+ if (re && !re.test(text)) return { ok: false, reason: 'require' }
120
+ }
121
+
122
+ const deny = Array.isArray(cfg?.ownerSourceDeny) ? cfg.ownerSourceDeny : []
123
+ for (const pattern of deny) {
124
+ if (typeof pattern !== 'string' || !pattern) continue
125
+ let re
126
+ try {
127
+ re = new RegExp(pattern, 'u')
128
+ } catch {
129
+ continue
130
+ }
131
+ if (re.test(text)) return { ok: false, reason: 'deny' }
132
+ }
133
+ return { ok: true, reason: null }
134
+ }
135
+
136
+ /** 从事件流里挑最近一条「真·他说的话」。 */
137
+ export function pickLastUserMessage(events, cfg, options = {}) {
138
+ const maxScan = Number.isFinite(options.maxScan) && options.maxScan > 0 ? Math.floor(options.maxScan) : 400
139
+ const spliceIndex = buildSpliceIndex(events)
140
+ const skipped = { kind: 0, require: 0, deny: 0 }
141
+ let scanned = 0
142
+ let newest = null
143
+
144
+ for (let i = events.length - 1; i >= 0; i -= 1) {
145
+ const event = events[i]
146
+ if (event.type !== 'user/message') continue
147
+ const text = textOfContent(event.data?.content)
148
+ if (!text.trim()) continue
149
+ if (scanned >= maxScan) break
150
+ scanned += 1
151
+
152
+ const spliced = spliceIndex.get(spliceKey(text))
153
+ const kind = spliced?.kind ?? (typeof event.data?.source?.kind === 'string' ? event.data.source.kind : 'user')
154
+ const verdict = judge(text, kind, cfg)
155
+ if (verdict.ok) {
156
+ newest = {
157
+ at: Number(event.time) || null,
158
+ kind,
159
+ channel: channelOf({ kind, form: spliced?.form }),
160
+ text,
161
+ seq: event.seq ?? null,
162
+ }
163
+ break
164
+ }
165
+ if (verdict.reason && verdict.reason in skipped) skipped[verdict.reason] += 1
166
+ }
167
+
168
+ return { found: Boolean(newest), message: newest, scanned, skipped }
169
+ }
170
+
171
+ /** 最后一条 user 消息与最后一条 assistant 消息的时间(不看闸,只问「谁最后说话」) */
172
+ export function pickTimeline(events) {
173
+ let lastUserAt = null
174
+ let lastAssistantAt = null
175
+ for (let i = events.length - 1; i >= 0; i -= 1) {
176
+ if (lastUserAt !== null && lastAssistantAt !== null) break
177
+ const event = events[i]
178
+ const at = Number(event?.time) || null
179
+ if (!at) continue
180
+ if (lastAssistantAt === null && event.type === 'assistant/message') lastAssistantAt = at
181
+ if (lastUserAt === null && event.type === 'user/message') {
182
+ if (textOfContent(event.data?.content).trim()) lastUserAt = at
183
+ }
184
+ }
185
+ return { lastUserAt, lastAssistantAt }
186
+ }
187
+
188
+ export function preview(text) {
189
+ const flat = String(text || '').replace(/\s+/g, ' ').trim()
190
+ return flat.length > PREVIEW ? `${flat.slice(0, PREVIEW)}…` : flat
191
+ }
192
+
193
+ /** 会话目录名跟 cwd 编码有关,不猜:直接按 <sid>/session.v4.jsonl.zstd 找。 */
194
+ export async function findSessionLog(sessionsRoot, sessionId) {
195
+ let dirs
196
+ try {
197
+ dirs = await readdir(sessionsRoot, { withFileTypes: true })
198
+ } catch {
199
+ return null
200
+ }
201
+ for (const dirent of dirs) {
202
+ if (!dirent.isDirectory()) continue
203
+ const candidate = join(sessionsRoot, dirent.name, String(sessionId), 'session.v4.jsonl.zstd')
204
+ try {
205
+ await readFile(candidate, { encoding: null })
206
+ return candidate
207
+ } catch {
208
+ // 下一个
209
+ }
210
+ }
211
+ return null
212
+ }
213
+
214
+ export async function readSessionPresence(sessionsRoot, sessionId, cfg, options = {}) {
215
+ const file = await findSessionLog(sessionsRoot, sessionId)
216
+ if (!file) return { ok: false, error: 'no_log', sessionId, sessionsRoot }
217
+ const buffer = await readFile(file)
218
+ // 大日志(几十 MB)先只解最后几百帧;找不到再全量解一次
219
+ const tail = Number.isInteger(options.tailFrames) ? options.tailFrames : 300
220
+ let events = parseEvents(decodeLog(buffer, { maxFrames: tail }))
221
+ let picked = pickLastUserMessage(events, cfg, options)
222
+ if (!picked.found && options.allowFull !== false) {
223
+ events = parseEvents(decodeLog(buffer))
224
+ picked = pickLastUserMessage(events, cfg, options)
225
+ }
226
+ const timeline = pickTimeline(events)
227
+ return {
228
+ ok: true,
229
+ sessionId,
230
+ sessionFile: file,
231
+ bytes: buffer.length,
232
+ events: events.length,
233
+ ...timeline,
234
+ ...picked,
235
+ }
236
+ }
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Heartbeat",
4
+ "description": "A clock the model sets for itself: it wakes up in the same conversation and leaves a one-line notice. Switch, interval, time window, daily budget and a temporary mute."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "鱼的心跳",
4
+ "description": "自己的闹钟:模型自己定时间,到点在同一个会话里注一条提示;带开关、频次、时段、每日上限和临时静音。"
5
+ }
6
+ }