dsh-memu-memory 1.2.6 → 1.2.7

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.
@@ -0,0 +1,204 @@
1
+ // P1-1 召回缓存。
2
+ //
3
+ // 设计偏离说明:设计稿用 `lru-cache` npm 依赖,本仓库依赖极少且无构建步骤,
4
+ // 改为内置手写 LRU(Map 删除再插入实现新鲜度),不新增依赖。
5
+ //
6
+ // 失效模型(三层,见 lib/memory.js managedRecall 的接线注释):
7
+ // 1. TTL(默认 120s):兜底一切漏网——跨进程写入、expiresAt 到点、外部编辑。
8
+ // 2. 键内 revision/generation:调用方把 state.js memoryRevision()(所有索引/状态
9
+ // 写入在 saveXxxIndex/saveState 收敛处自增)和 captureGeneration() 的向量代数
10
+ // token 传进 recallCacheKey,任一变化键即变,旧条目自然失联。
11
+ // 3. bumpGeneration():缓存内部代数 +1,全部旧键立即失联——测试与运维的手动闸。
12
+ //
13
+ // fail-open 纪律(AGENTS.md §1 规则 10):缓存自身出错绝不影响召回。所有公开方法
14
+ // 内部 try/catch,出错按「未命中」处理并 errors++ 留痕;本模块不持有 logger,
15
+ // 通过 onError 回调(setErrorHandler,由 memory.js 接 warn)和 stats() 的
16
+ // errors/lastError 把真实故障暴露给调用方,绝不静默吞掉。
17
+
18
+ const SEP = '\u0000'
19
+
20
+ function cloneValue(value) {
21
+ // 缓存值必须是可 structuredClone 的纯数据(召回结果本就跨 RPC 序列化,满足)。
22
+ // 每次写入/读取都深拷贝:同一份缓存结果会被多个回合共享,克隆隔离调用方的就地
23
+ // 变异,避免一次变异污染后续所有命中。
24
+ return structuredClone(value)
25
+ }
26
+
27
+ export function createRecallCache({ max = 256, ttlMs = 120000, now = () => Date.now(), onError = null } = {}) {
28
+ const limit = Math.max(1, Math.floor(Number(max)) || 1)
29
+ const ttl = Math.max(0, Math.floor(Number(ttlMs)) || 0)
30
+ const clock = typeof now === 'function' ? now : () => Date.now()
31
+ const map = new Map() // key: gen + SEP + key → { value, expiresAt, query, gen }
32
+ const inflight = new Map() // key: gen + SEP + key → Promise(同 key 在途合并,防击穿)
33
+ let gen = 0
34
+ let hits = 0
35
+ let misses = 0
36
+ let evictions = 0
37
+ let errors = 0
38
+ let lastError = null
39
+
40
+ const fail = (op, error, key = null) => {
41
+ errors += 1
42
+ const message = String(error?.message || error)
43
+ lastError = op + ': ' + message
44
+ try { if (typeof onError === 'function') onError({ op, key, message }) } catch {}
45
+ }
46
+
47
+ const ckey = (key) => gen + SEP + String(key)
48
+
49
+ // 过期即删即逐出(计入 evictions),不参与命中。
50
+ const expired = (entry) => clock() >= entry.expiresAt
51
+
52
+ const peek = (ck) => {
53
+ const entry = map.get(ck)
54
+ if (!entry) return null
55
+ if (expired(entry)) {
56
+ map.delete(ck)
57
+ evictions += 1
58
+ return null
59
+ }
60
+ // LRU 新鲜度:命中即挪到 Map 尾部(删除再插入)。
61
+ map.delete(ck)
62
+ map.set(ck, entry)
63
+ return entry
64
+ }
65
+
66
+ const evictOverflow = () => {
67
+ while (map.size > limit) {
68
+ const oldest = map.keys().next().value
69
+ map.delete(oldest)
70
+ evictions += 1
71
+ }
72
+ }
73
+
74
+ const store = (ck, value) => {
75
+ if (value === undefined) return // undefined 视为「没有结果」,不缓存
76
+ const snapshot = cloneValue(value)
77
+ map.delete(ck)
78
+ // 条目归属的代数取自复合键前缀:在途 producer 在 bump 之后落地时,仍记旧代,
79
+ // 下一次 bump 会被清理,也永远不会被新代命中。
80
+ map.set(ck, { value: snapshot, expiresAt: clock() + ttl, gen: Number(ck.slice(0, ck.indexOf(SEP))) })
81
+ evictOverflow()
82
+ }
83
+
84
+ const cache = {
85
+ /** 命中返回深拷贝(可计数),未命中返回 null。 */
86
+ get(key) {
87
+ try {
88
+ const entry = peek(ckey(key))
89
+ if (!entry) { misses += 1; return null }
90
+ const value = cloneValue(entry.value)
91
+ hits += 1
92
+ return value
93
+ } catch (error) { fail('get', error, key); return null }
94
+ },
95
+ /** 写入失败(值不可克隆等)只计数不抛出;undefined 不缓存。 */
96
+ set(key, value) {
97
+ try { store(ckey(key), value) } catch (error) { fail('set', error, key) }
98
+ },
99
+ /** 全局代数 +1:旧代条目全部失联并清理,在途请求落回旧代键(无害失联)。 */
100
+ bumpGeneration() {
101
+ try {
102
+ gen += 1
103
+ for (const [ck, entry] of map) {
104
+ if (entry.gen !== gen) { map.delete(ck); evictions += 1 }
105
+ }
106
+ } catch (error) { fail('bumpGeneration', error) }
107
+ },
108
+ /** 按 query 精确失效。键是 recallCacheKey 的 JSON 串,解析出规范化 query 比对;
109
+ * 非 JSON 键跳过。返回失效条数。 */
110
+ invalidate(query) {
111
+ try {
112
+ const normalized = String(query ?? '').normalize('NFKC').trim().toLowerCase()
113
+ let removed = 0
114
+ for (const [ck, entry] of map) {
115
+ try {
116
+ if (JSON.parse(ck.slice(ck.indexOf(SEP) + 1)).query === normalized) {
117
+ map.delete(ck)
118
+ removed += 1
119
+ evictions += 1
120
+ }
121
+ } catch {}
122
+ }
123
+ return removed
124
+ } catch (error) { fail('invalidate', error, query); return 0 }
125
+ },
126
+ /** 清空 = 代数 +1 + 清理:在途 producer 落回旧代键,不会把旧值写进新代。 */
127
+ clear() {
128
+ try { cache.bumpGeneration() } catch (error) { fail('clear', error) }
129
+ },
130
+ /**
131
+ * 命中直接返回缓存值;未命中调 producer(可 async)并缓存;同 key 在途请求合并
132
+ * (promise 去重,防击穿,计入 hits)。producer 抛错不缓存、原样透传。
133
+ * 代数在进入 wrap 时捕获:在途期间发生 bump/clear,结果落回旧代键,不会污染新代。
134
+ */
135
+ wrap(key, producer) {
136
+ let ck = null
137
+ try {
138
+ ck = ckey(key)
139
+ const entry = peek(ck)
140
+ if (entry) {
141
+ const value = cloneValue(entry.value)
142
+ hits += 1
143
+ return value
144
+ }
145
+ } catch (error) { fail('wrap.get', error, key) }
146
+ if (ck !== null) {
147
+ const pending = inflight.get(ck)
148
+ if (pending) { hits += 1; return pending } // 在途合并:与命中同计
149
+ }
150
+ misses += 1
151
+ const run = (async () => {
152
+ const value = await producer()
153
+ if (ck !== null) {
154
+ try { store(ck, value) } catch (error) { fail('wrap.set', error, key) }
155
+ }
156
+ return value
157
+ })()
158
+ if (ck !== null) {
159
+ inflight.set(ck, run)
160
+ const settle = () => { inflight.delete(ck) }
161
+ run.then(settle, settle)
162
+ }
163
+ return run
164
+ },
165
+ stats() {
166
+ return { size: map.size, hits, misses, evictions, generations: gen, errors, lastError, inflight: inflight.size }
167
+ },
168
+ /** 接错误观察者(memory.js 接 warn,规则 10 的可观测信号)。 */
169
+ setErrorHandler(handler) {
170
+ try { onError = typeof handler === 'function' ? handler : null } catch (error) { fail('setErrorHandler', error) }
171
+ },
172
+ }
173
+ return cache
174
+ }
175
+
176
+ /**
177
+ * 缓存键:query 做 NFKC + trim + lowercase 规范化,其余字段定序 JSON.stringify。
178
+ * 除任务规定的 query/topK/libraryId/byId/route/generation 外,另含四个能改变融合
179
+ * 结果的输入(缺失记 null,保证同参同键):
180
+ * · revision — state.js memoryRevision(),索引/状态写入的进程内单调计数(写路径失效)
181
+ * · domain — globalRecall 按域预过滤、cross-library 按域裁剪索引
182
+ * · sessionId — fuseRecallCandidates 的 visibleToSession 按会话过滤
183
+ * · context — 绑定的 memoryContext(knownBy/characterId 改绑不改写索引,revision 不动)
184
+ * · automatic — fuseRecallCandidates 的 isMemoryEligible/secret 规则随它翻转
185
+ */
186
+ export function recallCacheKey({ query, topK, libraryId, byId, route, generation, revision, domain, automatic, sessionId, context } = {}) {
187
+ return JSON.stringify({
188
+ v: 1,
189
+ generation: generation ?? null,
190
+ revision: revision ?? null,
191
+ route: route ?? null,
192
+ libraryId: libraryId ?? null,
193
+ topK: Number(topK) || 0,
194
+ domain: domain ?? null,
195
+ automatic: automatic === true,
196
+ byId: byId === true,
197
+ sessionId: sessionId ?? null,
198
+ context: context ?? null,
199
+ query: String(query ?? '').normalize('NFKC').trim().toLowerCase(),
200
+ })
201
+ }
202
+
203
+ /** 模块级默认单例:memory.js 直接使用。 */
204
+ export const recallCache = createRecallCache()
package/lib/rpc.js CHANGED
@@ -11,6 +11,7 @@ import { commit, closeMemuResident, prewarmMemuResident } from './memu.js'
11
11
  import { privateList, privateUpdate, privateRemember, privateRecall, privateArchive, privateDelete, globalList, globalRecall, domainOf, decayStrength, appliesToDomain, importMemories, resolveMemoryReview, visibleToSession, isMemoryEligible } from './memory.js'
12
12
  import { normalizeMemoryContext } from './context.js'
13
13
  import { requestPrivateConsolidation } from './private.js'
14
+ import { listHostModelOptions, discoverForkModels, redactConsolidationSettings, disposeConsolidationRoute } from './fork-model.js'
14
15
  import { startGlobalCuration, getCurationJob, cancelCurationJob, listCurationJobs, undoGlobalAbsorb } from './curator.js'
15
16
  import { maybeMigrateLibraries } from './migrate.js'
16
17
  import { getPromptStates, savePromptOverride, resetPrompt, resetAllPrompts } from './prompts.js'
@@ -686,7 +687,7 @@ async function dispatch(ctx, endpoint, payload = {}) {
686
687
  engine: engineView(),
687
688
  memuConfig: getMemuConfig(),
688
689
  summaryConfig: getSummaryConfig(),
689
- settings: getSettings(),
690
+ settings: redactConsolidationSettings(getSettings()),
690
691
  libraries: libraryView(),
691
692
  archivedLibraries: archivedLibraryView(),
692
693
  binding: bindingView(binding),
@@ -921,7 +922,7 @@ async function dispatch(ctx, endpoint, payload = {}) {
921
922
  summaryConfig: getSummaryConfig(),
922
923
  visionConfig: getVisionConfig(),
923
924
  localVector: getLocalVectorState(),
924
- settings: getSettings(),
925
+ settings: redactConsolidationSettings(getSettings()),
925
926
  libraries: libraryView(),
926
927
  archivedLibraries: archivedLibraryView(),
927
928
  // Seeds the settings pane's heartbeat with the paint it just made, so the
@@ -1004,8 +1005,11 @@ async function dispatch(ctx, endpoint, payload = {}) {
1004
1005
  // 工单 C/D/E 的调参:没进这张表的 key 会被静默丢弃,设置页就成了死控件。
1005
1006
  'openLoopRemindDays', 'freshnessHint', 'freshnessDays',
1006
1007
  'salientWake', 'salientWakeHour', 'salientWakeTimeZone',
1008
+ // 整理 fork 的模型选择(三模式):恢复默认 = 回到 inherit,不留 host/custom 残配置。
1009
+ 'consolidationModelMode', 'consolidationModel',
1010
+ 'consolidationCustomBaseURL', 'consolidationCustomApiKey', 'consolidationCustomModel', 'consolidationCustomApi',
1007
1011
  ]) patch[key] = DEFAULT_SETTINGS[key]
1008
- return updateSettings(patch)
1012
+ return redactConsolidationSettings(updateSettings(patch))
1009
1013
  }
1010
1014
  case 'setSettings': {
1011
1015
  const patch = payload?.patch && typeof payload.patch === 'object' ? payload.patch : {}
@@ -1026,10 +1030,30 @@ async function dispatch(ctx, endpoint, payload = {}) {
1026
1030
  // 工单 C/D/E:未了之事复提节奏、时效提示、日期唤醒。缺一个就是设置页写了不生效。
1027
1031
  'openLoopRemindDays', 'freshnessHint', 'freshnessDays',
1028
1032
  'salientWake', 'salientWakeHour', 'salientWakeTimeZone',
1033
+ // 整理 fork 的模型选择:三模式开关 + host 指名 + custom 连接面(含明文 key 的
1034
+ // 写入;回包经 redactConsolidationSettings 打码,明文只落 state.json)。
1035
+ 'consolidationModelMode', 'consolidationModel',
1036
+ 'consolidationCustomBaseURL', 'consolidationCustomApiKey', 'consolidationCustomModel', 'consolidationCustomApi',
1029
1037
  ])
1030
1038
  const clean = {}
1031
1039
  for (const [k, v] of Object.entries(patch)) if (allowed.has(k)) clean[k] = v
1032
- return updateSettings(clean)
1040
+ return redactConsolidationSettings(updateSettings(clean))
1041
+ }
1042
+ case 'listForkModelOptions': {
1043
+ // 整理 fork 模型选择器的数据源:宿主已激活 route 的 provider/model 目录 +
1044
+ // custom/discovery 能力位。llm service 缺席返回空目录,设置页照常渲染。
1045
+ return await listHostModelOptions(ctx)
1046
+ }
1047
+ case 'discoverForkModels': {
1048
+ // UI「拉取模型列表」:把草稿端点转给宿主模型发现(dsh-llm-pi-ai)。apiKey 是
1049
+ // 一次性草稿凭据(或 useStoredKey 复用已保存的 custom key),只进发现请求,
1050
+ // 不进日志、不进回包;结果/错误都是结构化的,UI 直接渲染。
1051
+ return await discoverForkModels(ctx, {
1052
+ baseURL: payload?.baseURL,
1053
+ api: payload?.api,
1054
+ apiKey: payload?.apiKey,
1055
+ useStoredKey: payload?.useStoredKey === true,
1056
+ }, getSettings())
1033
1057
  }
1034
1058
  case 'setSessionScope': {
1035
1059
  const sessionId = requireSessionId(payload)
@@ -2088,6 +2112,13 @@ export function registerRpc(ctx) {
2088
2112
  'dsh-memu-memory: rpc',
2089
2113
  )
2090
2114
  try { c.logger?.info?.(`dsh-memu-memory: rpc route ${ENDPOINT} registered`) } catch {}
2115
+ // 自定义整理 route 的进程级清理(lib/fork-model.js):plugin 卸载/停用时把在宿主
2116
+ // llm 注册表挂的 dsh-memu-custom route 卸下来。幂等;未注册时是 no-op。这里没有
2117
+ // index.js 的改动额度,registerRpc 恰好拥有一个随宿主作用域 dispose 的 effect 面,
2118
+ // 生命周期跟随 RPC 注册体走是等价的。
2119
+ if (typeof c.effect === 'function') {
2120
+ c.effect(() => disposeConsolidationRoute, 'dsh-memu-memory: consolidation route')
2121
+ }
2091
2122
  })
2092
2123
  } catch (error) {
2093
2124
  try { ctx.logger?.warn?.(`dsh-memu-memory: rpc unavailable: ${error?.message || error}`) } catch {}
package/lib/state.js CHANGED
@@ -132,6 +132,19 @@ export const DEFAULT_SETTINGS = {
132
132
  salientWake: 'off',
133
133
  salientWakeHour: '09:00',
134
134
  salientWakeTimeZone: '',
135
+ // 整理 fork 的模型选择(三模式)。'inherit' 沿用父会话的 provider/model;'host' 用
136
+ // consolidationModel("<provider>/<model>",同 curatorModel 的解析口径)指名宿主已
137
+ // 激活的 route;'custom' 用 consolidationCustom* 在宿主 llm 注册表挂本插件私有 route
138
+ // (lib/fork-model.js CONSOLIDATION_CUSTOM_ROUTE)。fork 的 AgentOptions 没有
139
+ // baseURL/apiKey 通道,自定义端点只能走注册 route,所以 custom 的连接四件套存在这里。
140
+ // apiKey 落盘在 state.json(与 ~/.memu/config.env 的 0600 同一信任域),但任何 RPC
141
+ // 回包只给 has/tail 打码视图——rpc.js 的 redactConsolidationSettings。
142
+ consolidationModelMode: 'inherit',
143
+ consolidationModel: null,
144
+ consolidationCustomBaseURL: '',
145
+ consolidationCustomApiKey: '',
146
+ consolidationCustomModel: '',
147
+ consolidationCustomApi: 'openai-completions',
135
148
  // A positive age marks cleanup candidates; deletion always needs a user action.
136
149
  purgeArchivedAfterDays: 0,
137
150
  }
@@ -375,7 +388,7 @@ export function updateSettings(patch) {
375
388
  activeMemoryMinScore: [0, 10], activeMemoryStarvationMinutes: [1, 1440],
376
389
  activeMemoryCooldownMinutes: [0, 10080], activeMemoryRecallCooldownMinutes: [0, 10080],
377
390
  }
378
- 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'] }
391
+ 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'], consolidationModelMode: ['inherit', 'host', 'custom'], consolidationCustomApi: ['openai-completions', 'openai-responses', 'anthropic-messages'] }
379
392
  for (const [key, value] of Object.entries(patch || {})) {
380
393
  if (!Object.hasOwn(DEFAULT_SETTINGS, key)) continue
381
394
  if (enums[key]) {
@@ -391,6 +404,35 @@ export function updateSettings(patch) {
391
404
  } else if (key === 'curatorModel') {
392
405
  if (value !== null && (typeof value !== 'string' || value.length > 200)) throw new Error('invalid curator model')
393
406
  clean[key] = value
407
+ } else if (key === 'consolidationModel') {
408
+ // host 模式的 "<provider>/<model>"。格式本身留给 lib/fork-model.js 的解析口径
409
+ // (与 curatorModel 一致:这里只挡类型与超长),写错的值会在 fork 创建时被
410
+ // invalid-consolidation-model 拒绝并在活动日志里说清,设置页先存的草稿不该被卡死。
411
+ if (value !== null && (typeof value !== 'string' || value.length > 200)) throw new Error('invalid consolidation model')
412
+ clean[key] = value
413
+ } else if (key === 'consolidationCustomBaseURL') {
414
+ // custom 模式的端点。空串是「还没填」,合法;非空必须是不带内嵌凭据的 http(s)
415
+ // URL——与 pipIndexes / vision endpoint 同一把尺(宿主请求头进不了带凭据的 URL)。
416
+ if (typeof value !== 'string') throw new Error('setting consolidationCustomBaseURL must be a string')
417
+ const trimmed = value.trim()
418
+ if (trimmed) {
419
+ try {
420
+ const url = new URL(trimmed)
421
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) throw new Error('bad protocol')
422
+ } catch {
423
+ throw new Error('consolidationCustomBaseURL must be an HTTP(S) URL without embedded credentials')
424
+ }
425
+ }
426
+ clean[key] = trimmed
427
+ } else if (key === 'consolidationCustomApiKey') {
428
+ // custom 模式选填的明文 key(本地网关可以没有)。落盘在 state.json,回包只给
429
+ // 打码视图(rpc.js);这里只挡类型与荒谬长度,两头空白顺手去掉。
430
+ if (typeof value !== 'string' || value.length > 500) throw new Error('invalid consolidation custom api key')
431
+ clean[key] = value.trim()
432
+ } else if (key === 'consolidationCustomModel') {
433
+ // custom 模式必填的模型 id。允许 '/'(openrouter 风格的嵌套 id),只挡类型与长度。
434
+ if (typeof value !== 'string' || value.length > 200) throw new Error('invalid consolidation custom model')
435
+ clean[key] = value.trim()
394
436
  } else if (key === 'salientWakeHour') {
395
437
  // 定时唤醒的本地墙上时间。只收 HH:mm,不收 "9:00":宿主的 at 输入按 HH:mm[:ss]
396
438
  // 解释,少一位会被拒或读成别的时刻,宁可在设置页就拒绝。