dsh-memu-memory 1.2.2 → 1.2.3
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/AGENTS.md +3 -1
- package/README.md +12 -4
- package/README.zh.md +13 -5
- package/docs/client-conventions.md +1 -0
- package/docs/contributing.md +7 -6
- package/docs/emotion-model-spec.md +2 -2
- package/docs/env-and-commands.md +20 -0
- package/docs/host-api.md +19 -0
- package/docs/memory-semantics.md +10 -1
- package/docs/troubleshooting.md +36 -3
- package/lib/activity-log.js +1 -1
- package/lib/binding-diagnostics.js +1 -1
- package/lib/client.js +152 -9
- package/lib/cycle.js +9 -1
- package/lib/freshness.js +97 -0
- package/lib/graph.js +244 -2
- package/lib/inject.js +119 -8
- package/lib/memory.js +83 -17
- package/lib/rpc.js +13 -2
- package/lib/salient-wake.js +402 -0
- package/lib/state.js +92 -1
- package/package.json +1 -1
- package/scripts/drive-session.mjs +853 -0
- package/scripts/mock-llm.mjs +903 -0
- package/tests/client-render.test.mjs +13 -1
- package/tests/entity-merge.test.mjs +261 -0
- package/tests/fixtures/mock-llm/reply.txt +1 -0
- package/tests/freshness.test.mjs +140 -0
- package/tests/help-page.test.mjs +4 -4
- package/tests/injection-chain.test.mjs +176 -0
- package/tests/mock-llm.test.mjs +225 -0
- package/tests/open-loop-date.test.mjs +406 -0
- package/tests/salient-wake.test.mjs +362 -0
- package/tests/settings-plumbing.test.mjs +76 -0
- package/tests/sidebar.test.mjs +5 -1
- package/tests/stubs/dsh-schedule.js +105 -0
- package/tests/webui-auth.test.mjs +4 -0
|
@@ -0,0 +1,402 @@
|
|
|
1
|
+
// 工单 E:纪念日到点唤醒(todolist #1)。
|
|
2
|
+
//
|
|
3
|
+
// 用宿主公开的 `ctx.schedule` 在**投递时区**(`salientWakeTimeZone`,留空跟随系统)的今天/
|
|
4
|
+
// 明天到点时,给绑定会话排一条一次性任务。日期与「这一刻过去了吗」都按那个时区算,不然配置
|
|
5
|
+
// 时区与机器时区不一致时会排错一天,或把还没到的时刻当成已过而静默跳过。
|
|
6
|
+
// schedule 的投递是 `agent.followup(createUserMessage({source:{kind:'schedule'}}))`,
|
|
7
|
+
// 会开一整回合,而本插件的注入只认 `source.kind === 'user'` 的真实用户消息 —— 所以
|
|
8
|
+
// 这一回合拿不到锚点、召回或纪念日块,prompt 必须自包含。
|
|
9
|
+
//
|
|
10
|
+
// 这个 pass 只做三件事:读索引找出今天/明天要提的日期记忆、按 `memu:due:` 标题做
|
|
11
|
+
// 幂等、把任务交给宿主。它从不抛错(宿主可能根本没有 schedule 服务),也从不覆盖
|
|
12
|
+
// 用户的显式操作(暂停的任务不恢复),更不会把正文写进 prompt。没有任何会话需要
|
|
13
|
+
// 提醒时它连 `schedule.list` 都不发——空闲装机不该每 5 分钟碰一次宿主的任务表。
|
|
14
|
+
//
|
|
15
|
+
// 返回值有两种形状,调用方要同时接受:
|
|
16
|
+
// - 整个 pass 没跑:`{ skipped: '<off|service|timezone|time>' }`
|
|
17
|
+
// - 跑过一轮:`{ created, cleaned, skipped, errors }`(都是计数)
|
|
18
|
+
import { getSettings, listSessionBindings, loadPrivateIndex, effectiveScope } from './state.js'
|
|
19
|
+
import {
|
|
20
|
+
isDatedSalientDate, isMemoryEligible, salientDateFires, salientDaysAhead, visibleToSession,
|
|
21
|
+
} from './memory.js'
|
|
22
|
+
import { record } from './activity-log.js'
|
|
23
|
+
|
|
24
|
+
const DEFAULT_HOUR = '09:00'
|
|
25
|
+
const HOUR_RE = /^([01]\d|2[0-3]):[0-5]\d$/
|
|
26
|
+
// 宿主 list 的上限是 500(types.ts `ScheduleListRequest.limit` 1-500)。一次 sweep
|
|
27
|
+
// 只读一页:这插件每会话每天最多两条任务,500 条已经远超正常装机量。
|
|
28
|
+
const LIST_LIMIT = 500
|
|
29
|
+
// 一条 prompt 最多列这么多条日期;其余用一句话指回 memu_private_recall,避免一个
|
|
30
|
+
// 大库把 schedule 回合的开场白撑成一页目录。
|
|
31
|
+
const MAX_LINES = 8
|
|
32
|
+
// 宿主拒绝投递的错误码里,这两种是"这个目标本来就不该有提醒",不是故障。
|
|
33
|
+
const SKIP_CODES = new Set(['subagent_session', 'invalid_rule'])
|
|
34
|
+
const KNOWN_CODES = [
|
|
35
|
+
'subagent_session', 'invalid_rule', 'invalid_time_zone', 'not_future', 'invalid_selector',
|
|
36
|
+
'invalid_prompt', 'time_out_of_range', 'frequency_too_high', 'internal_error',
|
|
37
|
+
]
|
|
38
|
+
|
|
39
|
+
// "一次 warn":宿主没有 schedule 服务是装机事实,不必每 5 分钟重复一遍日志。
|
|
40
|
+
let serviceWarned = false
|
|
41
|
+
// 坏时区按取值去重:同一串坏配置只吵一次,换成另一串再吵。
|
|
42
|
+
let zoneWarnedFor = null
|
|
43
|
+
|
|
44
|
+
function pad2(value) {
|
|
45
|
+
return String(value).padStart(2, '0')
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// 墙上时刻读取按 zone 复用 formatter:这条 pass 每 5 分钟跑一次,构造 Intl 对象不是免费的。
|
|
49
|
+
const wallFormatters = new Map()
|
|
50
|
+
|
|
51
|
+
function wallParts(instant, zone) {
|
|
52
|
+
let fmt = wallFormatters.get(zone)
|
|
53
|
+
if (!fmt) {
|
|
54
|
+
fmt = new Intl.DateTimeFormat('en-US', {
|
|
55
|
+
timeZone: zone, hourCycle: 'h23',
|
|
56
|
+
year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit',
|
|
57
|
+
})
|
|
58
|
+
wallFormatters.set(zone, fmt)
|
|
59
|
+
}
|
|
60
|
+
const parts = {}
|
|
61
|
+
for (const part of fmt.formatToParts(new Date(instant))) {
|
|
62
|
+
if (part.type !== 'literal') parts[part.type] = Number(part.value)
|
|
63
|
+
}
|
|
64
|
+
return parts
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* 某个绝对时刻在指定时区里落在哪个日历日,以及那天的「今天/明天」载体。
|
|
69
|
+
*
|
|
70
|
+
* 日期必须按**投递时区**算,不是系统时区:`salientWakeTimeZone` 填了 UTC 而机器在上海时,
|
|
71
|
+
* 用系统墙钟得到的「今天」比配置时区早一天,今天 09:00(UTC) 明明还没到也会被当成已过而静默跳过。
|
|
72
|
+
* 载体 Date 只用来喂 `salientDateFires`/`salientDaysAhead`(它们读 getMonth/getDate),正午锚点
|
|
73
|
+
* 避开夏令时在午夜附近造出的「这一天不存在 00:00」。
|
|
74
|
+
*/
|
|
75
|
+
export function dayInZone(instant, zone, offsetDays = 0) {
|
|
76
|
+
const w = wallParts(instant, zone)
|
|
77
|
+
const day = new Date(w.year, w.month - 1, w.day + offsetDays, 12, 0, 0, 0)
|
|
78
|
+
return { day, date: `${day.getFullYear()}-${pad2(day.getMonth() + 1)}-${pad2(day.getDate())}` }
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* 「该时区的 dateKey hour」对应的绝对毫秒。先把它当 UTC 猜一次,再用该时区在那个瞬间的偏移
|
|
83
|
+
* 修正;迭代到不动为止(DST 跳变时第二次才收敛),三次是上限兜底。
|
|
84
|
+
* 严格未来判断必须用它:宿主要按 `at.time_zone` 解释日期与时分。
|
|
85
|
+
*/
|
|
86
|
+
export function instantInZone(dateKey, hour, zone) {
|
|
87
|
+
const [year, month, day] = String(dateKey).split('-').map(Number)
|
|
88
|
+
const [hh, mm] = String(hour).split(':').map(Number)
|
|
89
|
+
const target = Date.UTC(year, month - 1, day, hh, mm, 0, 0)
|
|
90
|
+
if (!Number.isFinite(target)) return NaN
|
|
91
|
+
let instant = target
|
|
92
|
+
for (let i = 0; i < 3; i += 1) {
|
|
93
|
+
const w = wallParts(instant, zone)
|
|
94
|
+
const offset = Date.UTC(w.year, w.month - 1, w.day, w.hour, w.minute, w.second) - instant
|
|
95
|
+
const next = target - offset
|
|
96
|
+
if (next === instant) break
|
|
97
|
+
instant = next
|
|
98
|
+
}
|
|
99
|
+
return instant
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// 时区:显式配置优先,空串跟随系统。空或无效一律返回 null —— 少一条提醒,不是把
|
|
103
|
+
// 宿主的时间算错。
|
|
104
|
+
function resolveZone(settings) {
|
|
105
|
+
const configured = typeof settings?.salientWakeTimeZone === 'string' ? settings.salientWakeTimeZone.trim() : ''
|
|
106
|
+
let zone = configured
|
|
107
|
+
if (!zone) {
|
|
108
|
+
try { zone = String(Intl.DateTimeFormat().resolvedOptions().timeZone || '') } catch { zone = '' }
|
|
109
|
+
}
|
|
110
|
+
if (!zone) return null
|
|
111
|
+
try {
|
|
112
|
+
new Intl.DateTimeFormat('en-US', { timeZone: zone })
|
|
113
|
+
return zone
|
|
114
|
+
} catch {
|
|
115
|
+
return null
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function resolveHour(settings) {
|
|
120
|
+
const hour = String(settings?.salientWakeHour ?? '')
|
|
121
|
+
if (HOUR_RE.test(hour)) return { hour, fallback: false }
|
|
122
|
+
return { hour: DEFAULT_HOUR, fallback: true }
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// 宿主会把这些拒绝原样抛成 `ScheduleInputError`(本地服务)或带 details 的
|
|
126
|
+
// `RemoteError`(远程传输),两边的 code 位置不同,所以逐个探。
|
|
127
|
+
function scheduleErrorCode(error) {
|
|
128
|
+
for (const value of [error?.code, error?.details?.code, error?.data?.code]) {
|
|
129
|
+
if (typeof value === 'string' && value) return value
|
|
130
|
+
}
|
|
131
|
+
const text = String(error?.message || error || '')
|
|
132
|
+
return KNOWN_CODES.find((code) => text.includes(code)) || ''
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function safeTitle(entry) {
|
|
136
|
+
// 标题进的是另一回合的开场白:压平换行,别让一条记忆在 prompt 里伪造出新的行。
|
|
137
|
+
const text = String(entry?.title || '').replace(/\s+/g, ' ').trim()
|
|
138
|
+
return (text || '(untitled)').slice(0, 120)
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// 相对"投递日"的措辞:ahead 0 = 今天,ahead 1 = 明天(保留提前一天的语义)。
|
|
142
|
+
// 年度日期只在当天触发,因此永远是"今天"。
|
|
143
|
+
function whenLabel(entry, day) {
|
|
144
|
+
if (!isDatedSalientDate(entry?.salientDate)) return '今天'
|
|
145
|
+
return salientDaysAhead(entry.salientDate, day) === 1 ? '明天' : '今天'
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function entryLine({ entry }, day) {
|
|
149
|
+
const when = whenLabel(entry, day)
|
|
150
|
+
const annual = !isDatedSalientDate(entry?.salientDate)
|
|
151
|
+
const date = annual ? `每年 ${String(entry?.salientDate || '')}` : String(entry?.salientDate || '')
|
|
152
|
+
const title = safeTitle(entry)
|
|
153
|
+
// 承诺和日程的语气不同,与 lib/inject.js 的 `<memory-due>` 保持一致:答应了又
|
|
154
|
+
// 没做的事听起来是欠账,不是事件。正文一律不进 prompt —— 标题就是目录。
|
|
155
|
+
if (entry?.openLoop === true) return `- ${when}:你之前答应过的「${title}」,就是${when}(${date})。`
|
|
156
|
+
return `- ${when}:${title}(${date})。`
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function buildPrompt({ dateKey, day, hits }) {
|
|
160
|
+
const lines = [`[dsh-memu-memory 日期提醒] 本轮日期 ${dateKey}。今天/明天是:`]
|
|
161
|
+
for (const hit of hits.slice(0, MAX_LINES)) lines.push(entryLine(hit, day))
|
|
162
|
+
if (hits.length > MAX_LINES) lines.push(`- 另有 ${hits.length - MAX_LINES} 条日期记忆,用 memu_private_recall 查。`)
|
|
163
|
+
// schedule 回合不触发本插件注入,所以这句是唯一的上下文来源;"不要重复"是宿主
|
|
164
|
+
// at-least-once 投递的唯一缓冲。
|
|
165
|
+
lines.push('这是记忆里记下的日期;需要细节用 memu_private_recall 查。若你已经说过,不要重复。')
|
|
166
|
+
return lines.join('\n')
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// 与 `buildAnniversary` 同一套门:可自动注入、非 secret 正文、对本会话可见。
|
|
170
|
+
function dueEntries(index, sessionId, day, nowMs) {
|
|
171
|
+
const hits = []
|
|
172
|
+
for (const [id, entry] of Object.entries(index?.entries || {})) {
|
|
173
|
+
if (!entry || typeof entry !== 'object') continue
|
|
174
|
+
if (!entry.salientDate) continue
|
|
175
|
+
if (entry.visibility === 'secret') continue
|
|
176
|
+
if (!salientDateFires(entry.salientDate, day)) continue
|
|
177
|
+
if (!isMemoryEligible(entry, { automatic: true, now: nowMs })) continue
|
|
178
|
+
try {
|
|
179
|
+
if (!visibleToSession(entry, sessionId)) continue
|
|
180
|
+
} catch {
|
|
181
|
+
continue
|
|
182
|
+
}
|
|
183
|
+
hits.push({ id, entry })
|
|
184
|
+
}
|
|
185
|
+
hits.sort((a, b) => String(a.entry.salientDate).localeCompare(String(b.entry.salientDate))
|
|
186
|
+
|| String(a.entry.title || '').localeCompare(String(b.entry.title || '')))
|
|
187
|
+
return hits
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function byTitleIndex(items) {
|
|
191
|
+
const map = new Map()
|
|
192
|
+
for (const item of items) {
|
|
193
|
+
if (!item || typeof item.title !== 'string') continue
|
|
194
|
+
const list = map.get(item.title) || []
|
|
195
|
+
list.push(item)
|
|
196
|
+
map.set(item.title, list)
|
|
197
|
+
}
|
|
198
|
+
return map
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* One sweep of the salient-date wake pass (work order E).
|
|
203
|
+
*
|
|
204
|
+
* Creates one host schedule task per conversation and target date, titled
|
|
205
|
+
* `memu:due:<sessionId>:<YYYY-MM-DD>`, so a second sweep is a no-op. Never throws;
|
|
206
|
+
* a host without the optional `schedule` service is a skip, not a failure.
|
|
207
|
+
*
|
|
208
|
+
* @param {object} ctx host context (`ctx.get('schedule')` is optional)
|
|
209
|
+
* @param {{ now?: Date|number, log?: (message: string) => void }} [options]
|
|
210
|
+
* @returns {{ skipped: string } | { created: number, cleaned: number, skipped: number, errors: number }}
|
|
211
|
+
*/
|
|
212
|
+
export async function runSalientWakePass(ctx, { now = new Date(), log = () => {} } = {}) {
|
|
213
|
+
const notify = (message) => { try { log(message) } catch {} }
|
|
214
|
+
const stats = { created: 0, cleaned: 0, skipped: 0, errors: 0 }
|
|
215
|
+
try {
|
|
216
|
+
const settings = getSettings()
|
|
217
|
+
if (settings.salientWake !== 'schedule') return { skipped: 'off' }
|
|
218
|
+
|
|
219
|
+
let schedule = null
|
|
220
|
+
try { schedule = ctx?.get?.('schedule') || null } catch { schedule = null }
|
|
221
|
+
if (!schedule || typeof schedule.create !== 'function' || typeof schedule.list !== 'function') {
|
|
222
|
+
if (!serviceWarned) {
|
|
223
|
+
serviceWarned = true
|
|
224
|
+
notify('salient wake is enabled but this host exposes no schedule service; skipping')
|
|
225
|
+
record({
|
|
226
|
+
kind: 'wake', level: 'warn', ok: false,
|
|
227
|
+
message: '日期唤醒已启用,但宿主没有 schedule 服务;本轮跳过',
|
|
228
|
+
detail: { trigger: 'wake', stage: 'service' },
|
|
229
|
+
})
|
|
230
|
+
}
|
|
231
|
+
return { skipped: 'service' }
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
const when = now instanceof Date ? now : new Date(now)
|
|
235
|
+
if (!Number.isFinite(when.getTime())) return { skipped: 'time' }
|
|
236
|
+
|
|
237
|
+
const zone = resolveZone(settings)
|
|
238
|
+
if (!zone) {
|
|
239
|
+
const key = String(settings?.salientWakeTimeZone ?? '')
|
|
240
|
+
if (zoneWarnedFor !== key) {
|
|
241
|
+
zoneWarnedFor = key
|
|
242
|
+
notify(`salient wake skipped: no usable IANA time zone (configured ${JSON.stringify(key)})`)
|
|
243
|
+
record({
|
|
244
|
+
kind: 'wake', level: 'warn', ok: false,
|
|
245
|
+
message: '日期唤醒已跳过:时区为空或无效',
|
|
246
|
+
detail: { trigger: 'wake', stage: 'timezone', zone: key || null },
|
|
247
|
+
})
|
|
248
|
+
}
|
|
249
|
+
return { skipped: 'timezone' }
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
const { hour, fallback } = resolveHour(settings)
|
|
253
|
+
if (fallback) notify(`salient wake: invalid salientWakeHour ${JSON.stringify(settings?.salientWakeHour)}; using ${DEFAULT_HOUR}`)
|
|
254
|
+
|
|
255
|
+
// 先把"要提醒什么"算完:没有会话需要提醒时,一次宿主调用都不发。
|
|
256
|
+
const today = dayInZone(when.getTime(), zone, 0)
|
|
257
|
+
const tomorrow = dayInZone(when.getTime(), zone, 1)
|
|
258
|
+
const nowMs = when.getTime()
|
|
259
|
+
const plans = []
|
|
260
|
+
for (const binding of listSessionBindings()) {
|
|
261
|
+
const sessionId = binding?.sessionId
|
|
262
|
+
if (!sessionId || !binding.libraryId) continue
|
|
263
|
+
if (binding.useLibrary === false) continue
|
|
264
|
+
try {
|
|
265
|
+
if (!effectiveScope(binding).useLibrary) continue
|
|
266
|
+
} catch {
|
|
267
|
+
continue
|
|
268
|
+
}
|
|
269
|
+
let index
|
|
270
|
+
try {
|
|
271
|
+
index = loadPrivateIndex(binding.libraryId)
|
|
272
|
+
} catch (error) {
|
|
273
|
+
// 库没了/索引坏了:这一个会话跳过,其他会话照跑。
|
|
274
|
+
stats.errors += 1
|
|
275
|
+
const message = String(error?.message || error)
|
|
276
|
+
notify(`salient wake: cannot read library ${binding.libraryId}: ${message}`)
|
|
277
|
+
record({
|
|
278
|
+
kind: 'wake', scope: 'private', sessionId, libraryId: binding.libraryId, level: 'warn', ok: false,
|
|
279
|
+
message: '日期唤醒:读取记忆库失败:' + message,
|
|
280
|
+
detail: { trigger: 'wake', stage: 'index' },
|
|
281
|
+
})
|
|
282
|
+
continue
|
|
283
|
+
}
|
|
284
|
+
for (const target of [today, tomorrow]) {
|
|
285
|
+
const hits = dueEntries(index, sessionId, target.day, nowMs)
|
|
286
|
+
if (hits.length === 0) continue
|
|
287
|
+
plans.push({ sessionId, libraryId: binding.libraryId, target: { ...target, hits } })
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
if (plans.length === 0) return stats
|
|
291
|
+
|
|
292
|
+
let items = []
|
|
293
|
+
try {
|
|
294
|
+
const page = await schedule.list({ limit: LIST_LIMIT })
|
|
295
|
+
items = Array.isArray(page?.items) ? page.items : []
|
|
296
|
+
} catch (error) {
|
|
297
|
+
const message = String(error?.message || error)
|
|
298
|
+
stats.errors += 1
|
|
299
|
+
notify(`salient wake: schedule.list failed: ${message}`)
|
|
300
|
+
record({
|
|
301
|
+
kind: 'wake', level: 'warn', ok: false,
|
|
302
|
+
message: '日期唤醒:读取定时任务失败:' + message,
|
|
303
|
+
detail: { trigger: 'wake', stage: 'list', code: scheduleErrorCode(error) || null },
|
|
304
|
+
})
|
|
305
|
+
return stats
|
|
306
|
+
}
|
|
307
|
+
const byTitle = byTitleIndex(items)
|
|
308
|
+
|
|
309
|
+
for (const plan of plans) {
|
|
310
|
+
const { sessionId, libraryId, target } = plan
|
|
311
|
+
const title = `memu:due:${sessionId}:${target.date}`
|
|
312
|
+
const existing = byTitle.get(title) || []
|
|
313
|
+
// ended 的任务说明这一天的投递已经发生过(at-least-once),清掉即可,不再补建。
|
|
314
|
+
const ended = existing.filter((item) => item?.status === 'ended')
|
|
315
|
+
for (const item of ended) {
|
|
316
|
+
if (!item?.id) continue
|
|
317
|
+
try {
|
|
318
|
+
await schedule.edit({ id: item.id, action: 'delete' })
|
|
319
|
+
stats.cleaned += 1
|
|
320
|
+
notify(`salient wake: removed ended task ${item.id} (${title})`)
|
|
321
|
+
} catch (error) {
|
|
322
|
+
const message = String(error?.message || error)
|
|
323
|
+
stats.errors += 1
|
|
324
|
+
notify(`salient wake: could not remove ended task ${item.id}: ${message}`)
|
|
325
|
+
record({
|
|
326
|
+
kind: 'wake', scope: 'private', sessionId, libraryId, level: 'warn', ok: false,
|
|
327
|
+
message: '日期唤醒:清理已结束任务失败:' + message,
|
|
328
|
+
detail: { trigger: 'wake', stage: 'cleanup', title, code: scheduleErrorCode(error) || null },
|
|
329
|
+
})
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
// active 是幂等的证据;paused 是用户的显式暂停,绝不擅自恢复。
|
|
333
|
+
if (existing.some((item) => item?.status === 'active') || existing.some((item) => item?.status === 'paused')) {
|
|
334
|
+
stats.skipped += 1
|
|
335
|
+
continue
|
|
336
|
+
}
|
|
337
|
+
if (ended.length > 0) {
|
|
338
|
+
stats.skipped += 1
|
|
339
|
+
continue
|
|
340
|
+
}
|
|
341
|
+
// 严格未来:今天的 09:00 已经过去就不排今天(被动注入仍然会提),明天照排。
|
|
342
|
+
// 严格未来:按**投递时区**判断这一刻有没有过去。今天的 09:00 已经过去就不排今天
|
|
343
|
+
// (被动注入仍然会提),明天照排。
|
|
344
|
+
if (!(instantInZone(target.date, hour, zone) > when.getTime())) {
|
|
345
|
+
stats.skipped += 1
|
|
346
|
+
continue
|
|
347
|
+
}
|
|
348
|
+
const prompt = buildPrompt({ dateKey: target.date, day: target.day, hits: target.hits })
|
|
349
|
+
try {
|
|
350
|
+
const created = await schedule.create({
|
|
351
|
+
title,
|
|
352
|
+
prompt,
|
|
353
|
+
timing: { kind: 'at', at: { date: target.date, time: hour, time_zone: zone } },
|
|
354
|
+
target: { kind: 'session', sessionId },
|
|
355
|
+
})
|
|
356
|
+
stats.created += 1
|
|
357
|
+
byTitle.set(title, [...existing, created || { title, status: 'active' }])
|
|
358
|
+
notify(`salient wake: scheduled ${title} at ${target.date} ${hour} ${zone}`)
|
|
359
|
+
record({
|
|
360
|
+
kind: 'wake', scope: 'private', sessionId, libraryId, ok: true,
|
|
361
|
+
message: `日期唤醒已排程:${target.date} ${hour}(${target.hits.length} 条)`,
|
|
362
|
+
detail: {
|
|
363
|
+
trigger: 'wake', stage: 'create', date: target.date, hour, zone,
|
|
364
|
+
ids: target.hits.map((hit) => hit.id).slice(0, 20), taskId: created?.id || null,
|
|
365
|
+
},
|
|
366
|
+
})
|
|
367
|
+
} catch (error) {
|
|
368
|
+
const code = scheduleErrorCode(error)
|
|
369
|
+
const message = String(error?.message || error)
|
|
370
|
+
if (SKIP_CODES.has(code)) {
|
|
371
|
+
stats.skipped += 1
|
|
372
|
+
notify(`salient wake: ${title} skipped (${code})`)
|
|
373
|
+
record({
|
|
374
|
+
kind: 'wake', scope: 'private', sessionId, libraryId, ok: true,
|
|
375
|
+
message: `日期唤醒跳过(${code}):该目标不收 schedule 投递`,
|
|
376
|
+
detail: { trigger: 'wake', stage: 'create', title, code },
|
|
377
|
+
})
|
|
378
|
+
} else {
|
|
379
|
+
stats.errors += 1
|
|
380
|
+
notify(`salient wake: ${title} failed: ${message}`)
|
|
381
|
+
record({
|
|
382
|
+
kind: 'wake', scope: 'private', sessionId, libraryId, level: 'warn', ok: false,
|
|
383
|
+
message: '日期唤醒排程失败:' + message,
|
|
384
|
+
detail: { trigger: 'wake', stage: 'create', title, code: code || null },
|
|
385
|
+
})
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
return stats
|
|
390
|
+
} catch (error) {
|
|
391
|
+
// 兜底:这个 pass 的最后一道保险。循环里的每一步已经各自 try 过,走到这里说明
|
|
392
|
+
// 是没预料到的形状(例如 state.json 读到一半坏了),不能让 cycle 的 await 炸掉。
|
|
393
|
+
stats.errors += 1
|
|
394
|
+
notify(`salient wake pass failed: ${error?.message || error}`)
|
|
395
|
+
record({
|
|
396
|
+
kind: 'wake', level: 'warn', ok: false,
|
|
397
|
+
message: '日期唤醒整体失败:' + String(error?.message || error),
|
|
398
|
+
detail: { trigger: 'wake', stage: 'pass' },
|
|
399
|
+
})
|
|
400
|
+
return stats
|
|
401
|
+
}
|
|
402
|
+
}
|
package/lib/state.js
CHANGED
|
@@ -55,6 +55,11 @@ export const DEFAULT_SETTINGS = {
|
|
|
55
55
|
// chat actually says — recall was off in exactly the conversations that wanted
|
|
56
56
|
// it. "嗯" / "好" / "收到" (2-3 chars) still skip.
|
|
57
57
|
minUserChars: 6,
|
|
58
|
+
// 条件式时效提示(工单 D):召回块里出现可能过时的记忆时,在末尾追加一个
|
|
59
|
+
// <memory-freshness>,让有搜索工具的模型先核实,没有就如实说明。默认开;
|
|
60
|
+
// freshnessDays 是"写得够久"的口径,不在模块里另设默认。
|
|
61
|
+
freshnessHint: true,
|
|
62
|
+
freshnessDays: 30,
|
|
58
63
|
// Keep the always-on layer tight: dense chat generates many small candidates,
|
|
59
64
|
// and 16 pins would eat the anchor budget before the anchor starts.
|
|
60
65
|
mustRememberCap: 12,
|
|
@@ -115,6 +120,16 @@ export const DEFAULT_SETTINGS = {
|
|
|
115
120
|
memoryBackend: 'agent',
|
|
116
121
|
vectorSource: 'local',
|
|
117
122
|
habitsInjection: true,
|
|
123
|
+
// 一次性的带日期承诺过期之后的复提间隔(天)。带日期 + open_loop 的过期条目不走
|
|
124
|
+
// 3 天年龄门槛,也不会因为“提过一次”永久沉默;它按这个间隔重复,直到被关闭或归档。
|
|
125
|
+
// 它和普通 3 天腿共用每回合 limit 1,dated 过期腿优先。
|
|
126
|
+
openLoopRemindDays: 7,
|
|
127
|
+
// 工单 E:纪念日到点唤醒。它真的会改变宿主行为——用公开的 ctx.schedule 在绑定会话里
|
|
128
|
+
// 开一整回合——所以默认关闭,必须由用户显式打开。salientWakeHour 是该回合的本地墙上
|
|
129
|
+
// 时间(HH:mm);salientWakeTimeZone 为空表示跟随系统时区,非空必须是有效 IANA 区。
|
|
130
|
+
salientWake: 'off',
|
|
131
|
+
salientWakeHour: '09:00',
|
|
132
|
+
salientWakeTimeZone: '',
|
|
118
133
|
// A positive age marks cleanup candidates; deletion always needs a user action.
|
|
119
134
|
purgeArchivedAfterDays: 0,
|
|
120
135
|
}
|
|
@@ -350,13 +365,15 @@ export function updateSettings(patch) {
|
|
|
350
365
|
privateTopK: [1, 20], globalTopK: [1, 20], anchorTokens: [160, 8000], turnTokens: [80, 8000],
|
|
351
366
|
injectionTotalTokens: [160, 16000],
|
|
352
367
|
relevanceThreshold: [0, 1], dedupeTurns: [0, 200], globalEveryNTurns: [0, 200], minUserChars: [0, 1000],
|
|
368
|
+
freshnessDays: [1, 3650],
|
|
353
369
|
mustRememberCap: [1, 100], randomCueChance: [0, 1], shortTermTtlHours: [0, 8760],
|
|
354
370
|
unpinBudgetPerSession: [1, 20], unpinCooldownMinutes: [0, 1440], sleepAfterIdleMinutes: [1, 1440],
|
|
371
|
+
openLoopRemindDays: [1, 365],
|
|
355
372
|
autoCurateEveryHours: [0, 8760], autoCurateSessionLimit: [1, 10], purgeArchivedAfterDays: [0, 36500],
|
|
356
373
|
activeMemoryMinScore: [0, 10], activeMemoryStarvationMinutes: [1, 1440],
|
|
357
374
|
activeMemoryCooldownMinutes: [0, 10080], activeMemoryRecallCooldownMinutes: [0, 10080],
|
|
358
375
|
}
|
|
359
|
-
const enums = { autoInject: ['smart', 'anchor-only', 'per-turn', 'off'], memoryMode: ['local', 'cloud'], memoryBackend: ['agent', 'api'], vectorSource: ['local', 'api'], newSessionDefault: ['off', 'auto', 'global', 'both'], curatorReviewMode: ['auto', 'review-all'] }
|
|
376
|
+
const enums = { autoInject: ['smart', 'anchor-only', 'per-turn', 'off'], memoryMode: ['local', 'cloud'], memoryBackend: ['agent', 'api'], vectorSource: ['local', 'api'], newSessionDefault: ['off', 'auto', 'global', 'both'], curatorReviewMode: ['auto', 'review-all'], salientWake: ['off', 'schedule'] }
|
|
360
377
|
for (const [key, value] of Object.entries(patch || {})) {
|
|
361
378
|
if (!Object.hasOwn(DEFAULT_SETTINGS, key)) continue
|
|
362
379
|
if (enums[key]) {
|
|
@@ -372,6 +389,24 @@ export function updateSettings(patch) {
|
|
|
372
389
|
} else if (key === 'curatorModel') {
|
|
373
390
|
if (value !== null && (typeof value !== 'string' || value.length > 200)) throw new Error('invalid curator model')
|
|
374
391
|
clean[key] = value
|
|
392
|
+
} else if (key === 'salientWakeHour') {
|
|
393
|
+
// 定时唤醒的本地墙上时间。只收 HH:mm,不收 "9:00":宿主的 at 输入按 HH:mm[:ss]
|
|
394
|
+
// 解释,少一位会被拒或读成别的时刻,宁可在设置页就拒绝。
|
|
395
|
+
if (typeof value !== 'string' || !/^([01]\d|2[0-3]):[0-5]\d$/.test(value)) throw new Error('setting salientWakeHour must be HH:mm')
|
|
396
|
+
clean[key] = value
|
|
397
|
+
} else if (key === 'salientWakeTimeZone') {
|
|
398
|
+
// 空串是"跟随系统",是合法配置,不在这里解析成具体城市;非空必须是有效 IANA 区,
|
|
399
|
+
// 否则宿主的 at 计时会在投递时被拒(invalid_time_zone),排了也不会响。
|
|
400
|
+
if (typeof value !== 'string' || value.length > 100) throw new Error('invalid salientWakeTimeZone')
|
|
401
|
+
const zone = value.trim()
|
|
402
|
+
if (zone) {
|
|
403
|
+
try {
|
|
404
|
+
new Intl.DateTimeFormat('en-US', { timeZone: zone })
|
|
405
|
+
} catch {
|
|
406
|
+
throw new Error(`invalid salientWakeTimeZone: ${zone}`)
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
clean[key] = zone
|
|
375
410
|
} else if (key === 'pipIndexes' || key === 'promptDomains' || key === 'inboundToolNames') {
|
|
376
411
|
if (!Array.isArray(value) || value.length > 20 || value.some(item => typeof item !== 'string')) throw new Error(`invalid setting ${key}`)
|
|
377
412
|
if (key === 'promptDomains' && value.some(item => !/^[a-z0-9][a-z0-9_-]{0,23}$/.test(item))) throw new Error('invalid domain id')
|
|
@@ -953,6 +988,62 @@ export function markAnniversaryShown(sessionId, memoryId, dayKey) {
|
|
|
953
988
|
return setSessionBinding(sessionId, { anniversariesShown: fresh })
|
|
954
989
|
}
|
|
955
990
|
|
|
991
|
+
// ── repeated open loops ────────────────────────────────────────────────────────
|
|
992
|
+
// A dated promise that has already slipped its day keeps coming back on an interval
|
|
993
|
+
// instead of being forgotten. The regular 3-day nudge records its ids in
|
|
994
|
+
// `injectedIds`, which is right for "I already mentioned this once" and wrong for
|
|
995
|
+
// "it was never closed"; that is why the overdue leg keeps its own clock.
|
|
996
|
+
//
|
|
997
|
+
// `openLoopRemindedAt` maps memoryId -> ISO timestamp of the last time the overdue
|
|
998
|
+
// nudge actually reached the prompt. Entries older than 90 days are dropped on
|
|
999
|
+
// write so the map cannot grow without bound (an old key would not suppress
|
|
1000
|
+
// anything anyway — the interval has long elapsed).
|
|
1001
|
+
const OPEN_LOOP_REMIND_PRUNE_MS = 90 * 86_400_000
|
|
1002
|
+
|
|
1003
|
+
function localDayKeyOf(date) {
|
|
1004
|
+
const d = date instanceof Date ? date : new Date(date)
|
|
1005
|
+
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
|
|
1006
|
+
}
|
|
1007
|
+
|
|
1008
|
+
function prunedOpenLoopReminded(sessionId, now = new Date()) {
|
|
1009
|
+
const nowDate = now instanceof Date ? now : new Date(now)
|
|
1010
|
+
const nowMs = nowDate.getTime()
|
|
1011
|
+
const map = getSessionBinding(sessionId)?.openLoopRemindedAt
|
|
1012
|
+
const fresh = {}
|
|
1013
|
+
if (!map || typeof map !== 'object') return fresh
|
|
1014
|
+
for (const [memoryId, iso] of Object.entries(map)) {
|
|
1015
|
+
const at = Date.parse(String(iso || ''))
|
|
1016
|
+
if (!Number.isFinite(at)) continue
|
|
1017
|
+
if (nowMs - at > OPEN_LOOP_REMIND_PRUNE_MS) continue
|
|
1018
|
+
fresh[memoryId] = map[memoryId]
|
|
1019
|
+
}
|
|
1020
|
+
return fresh
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
/**
|
|
1024
|
+
* Whether an overdue open loop was already repeated on this local calendar day.
|
|
1025
|
+
* A session binding written before this field existed has no map: it is a first
|
|
1026
|
+
* reminder, not an error.
|
|
1027
|
+
*/
|
|
1028
|
+
export function wasOpenLoopRemindedToday(sessionId, memoryId, now = new Date()) {
|
|
1029
|
+
if (!sessionId || !memoryId) return false
|
|
1030
|
+
const iso = getSessionBinding(sessionId)?.openLoopRemindedAt?.[memoryId]
|
|
1031
|
+
const at = Date.parse(String(iso || ''))
|
|
1032
|
+
if (!Number.isFinite(at)) return false
|
|
1033
|
+
return localDayKeyOf(at) === localDayKeyOf(now)
|
|
1034
|
+
}
|
|
1035
|
+
|
|
1036
|
+
export function markOpenLoopReminded(sessionId, memoryId, at = new Date()) {
|
|
1037
|
+
if (!sessionId || !memoryId) return null
|
|
1038
|
+
// No binding means no conversation to remind; creating a stub from here would
|
|
1039
|
+
// write half a session into state.json.
|
|
1040
|
+
if (!getSessionBinding(sessionId)) return null
|
|
1041
|
+
const when = at instanceof Date ? at : new Date(at)
|
|
1042
|
+
const reminded = prunedOpenLoopReminded(sessionId, when)
|
|
1043
|
+
reminded[memoryId] = when.toISOString()
|
|
1044
|
+
return setSessionBinding(sessionId, { openLoopRemindedAt: reminded })
|
|
1045
|
+
}
|
|
1046
|
+
|
|
956
1047
|
export function memoryDbPath(libraryId) {
|
|
957
1048
|
ensureDir(librariesDir())
|
|
958
1049
|
return effectiveVectorRoute() === 'managed-local' ? memuDbFor(libraryId) : path.join(librariesDir(), `${libraryId}.sqlite3`)
|