dsh-memu-memory 1.2.5 → 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.
Files changed (56) hide show
  1. package/AGENTS.md +3 -1
  2. package/README.md +3 -3
  3. package/README.zh.md +3 -3
  4. package/docs/contributing.md +1 -1
  5. package/docs/env-and-commands.md +1 -0
  6. package/docs/host-adaptation.md +318 -0
  7. package/docs/host-api.md +29 -5
  8. package/docs/memory-semantics.md +12 -7
  9. package/docs/troubleshooting.md +15 -9
  10. package/lib/binding-diagnostics.js +2 -2
  11. package/lib/client.js +291 -37
  12. package/lib/consolidation-ledger.js +46 -1
  13. package/lib/consolidation-worker.js +1 -0
  14. package/lib/curator-policy.js +98 -0
  15. package/lib/cycle.js +51 -17
  16. package/lib/fork-model.js +312 -0
  17. package/lib/index.js +8 -0
  18. package/lib/memory.js +36 -12
  19. package/lib/memu.js +318 -3
  20. package/lib/private.js +352 -70
  21. package/lib/prompts/private-consolidation.mixed.md +1 -0
  22. package/lib/prompts/private-consolidation.rp.md +1 -0
  23. package/lib/prompts/private-policy.mixed.md +1 -0
  24. package/lib/prompts/private-policy.rp.md +1 -1
  25. package/lib/recall-cache.js +204 -0
  26. package/lib/rpc.js +48 -7
  27. package/lib/salient-wake.js +38 -2
  28. package/lib/state.js +46 -6
  29. package/lib/text-retrieval.js +221 -28
  30. package/lib/tokenizer-v2.js +295 -0
  31. package/lib/webui/standalone.css +17 -1
  32. package/package.json +1 -1
  33. package/scripts/bench-recall.mjs +142 -0
  34. package/scripts/check-seed-compat.mjs +118 -0
  35. package/tests/absorb-review.test.mjs +2 -1
  36. package/tests/backend-compensation.test.mjs +1 -1
  37. package/tests/consolidation-fork.test.mjs +199 -7
  38. package/tests/curator-absorb.test.mjs +2 -1
  39. package/tests/curator-clusters.test.mjs +9 -2
  40. package/tests/curator-commit.test.mjs +2 -1
  41. package/tests/curator-link.test.mjs +2 -1
  42. package/tests/curator-pairing.test.mjs +52 -8
  43. package/tests/curator-review-mode.test.mjs +2 -1
  44. package/tests/cycle.test.mjs +2 -2
  45. package/tests/dynamic-rrf.test.mjs +179 -0
  46. package/tests/fork-model.test.mjs +345 -0
  47. package/tests/loader.mjs +3 -0
  48. package/tests/managed-memory.test.mjs +1 -1
  49. package/tests/negation-polarity.test.mjs +135 -0
  50. package/tests/recall-cache.test.mjs +290 -0
  51. package/tests/recall-dedup.test.mjs +1 -1
  52. package/tests/salient-wake.test.mjs +28 -1
  53. package/tests/stubs/dsh-llm-pi-ai.js +13 -0
  54. package/tests/stubs/dsh-schedule.js +35 -0
  55. package/tests/tokenizer-v2.test.mjs +142 -0
  56. package/tests/ui-defaults.test.mjs +1 -1
@@ -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
@@ -7,10 +7,11 @@ import {
7
7
  backupDatabases, listBackups, restoreBackup, deleteBackup, globalDbPath, normalizeCwd, getWorkspacePolicy, listWorkspacePolicies, setWorkspacePolicy,
8
8
  storageHealth, effectiveScope, summarizeIndex, getPromptDomains, addPromptDomain, removePromptDomain, memoryRevision, memoryStamp, noteMemoryBeat,
9
9
  } from './state.js'
10
- import { commit } from './memu.js'
10
+ 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)
@@ -1744,6 +1768,9 @@ async function dispatch(ctx, endpoint, payload = {}) {
1744
1768
  case 'setup': {
1745
1769
  const status = engineStatus()
1746
1770
  if (status.status !== 'installing') {
1771
+ // A reinstall may replace the venv the resident interpreter is running from;
1772
+ // stop it first so Windows can rename/delete the old engine directory.
1773
+ closeMemuResident()
1747
1774
  void ensureEngine({ force: payload?.force === true, beforeSwitch: backupDatabases }).catch(() => {})
1748
1775
  }
1749
1776
  return { started: true, engine: engineView() }
@@ -1751,6 +1778,7 @@ async function dispatch(ctx, endpoint, payload = {}) {
1751
1778
  case 'switchEngine': {
1752
1779
  const version = String(payload?.version || '')
1753
1780
  if (!version) throw new Error('version is required')
1781
+ closeMemuResident()
1754
1782
  const result = await switchEngineVersion(version, {
1755
1783
  beforeSwitch: backupDatabases,
1756
1784
  force: payload?.force === true,
@@ -1813,8 +1841,14 @@ async function dispatch(ctx, endpoint, payload = {}) {
1813
1841
  }
1814
1842
  case 'getMemuConfig':
1815
1843
  return getMemuConfig()
1816
- case 'setEmbeddingSource':
1817
- return setEmbeddingSource(String(payload?.source || ''))
1844
+ case 'setEmbeddingSource': {
1845
+ const config = setEmbeddingSource(String(payload?.source || ''))
1846
+ // Local mode is the resident route: warm it as soon as the switch flips, and
1847
+ // release it when the user goes back to the remote API route.
1848
+ if (config?.source === 'local') void prewarmMemuResident()
1849
+ else closeMemuResident()
1850
+ return config
1851
+ }
1818
1852
  case 'saveMemuConfig':
1819
1853
  return saveMemuConfig({
1820
1854
  provider: payload?.provider,
@@ -2078,6 +2112,13 @@ export function registerRpc(ctx) {
2078
2112
  'dsh-memu-memory: rpc',
2079
2113
  )
2080
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
+ }
2081
2122
  })
2082
2123
  } catch (error) {
2083
2124
  try { ctx.logger?.warn?.(`dsh-memu-memory: rpc unavailable: ${error?.message || error}`) } catch {}
@@ -13,7 +13,7 @@
13
13
  // 提醒时它连 `schedule.list` 都不发——空闲装机不该每 5 分钟碰一次宿主的任务表。
14
14
  //
15
15
  // 返回值有两种形状,调用方要同时接受:
16
- // - 整个 pass 没跑:`{ skipped: '<off|service|timezone|time>' }`
16
+ // - 整个 pass 没跑:`{ skipped: '<off|service|schedule-api|timezone|time>' }`
17
17
  // - 跑过一轮:`{ created, cleaned, skipped, errors }`(都是计数)
18
18
  import { getSettings, listSessionBindings, loadPrivateIndex, effectiveScope } from './state.js'
19
19
  import {
@@ -38,9 +38,32 @@ const KNOWN_CODES = [
38
38
 
39
39
  // "一次 warn":宿主没有 schedule 服务是装机事实,不必每 5 分钟重复一遍日志。
40
40
  let serviceWarned = false
41
+ // 0.2.0/0.2.1 的 schedule 是会话级 API;本 pass 用的是 0.2.2 起的宿主级任务表。
42
+ // 这是能力差异,不是每次 sweep 的故障,同样只提醒一次。
43
+ let sessionScopedWarned = false
41
44
  // 坏时区按取值去重:同一串坏配置只吵一次,换成另一串再吵。
42
45
  let zoneWarnedFor = null
43
46
 
47
+ /**
48
+ * Which schedule API a host exposes.
49
+ *
50
+ * - `global`: 0.2.2+ creates a host-wide task from one request
51
+ * (`create(request)`, `list(request) -> { items }`, `edit({ id, action })`).
52
+ * - `session`: 0.2.0/0.2.1 binds every reminder to one session
53
+ * (`create(sessionId, request)`, `list({ sessionId }) -> array`, `delete({ sessionId, id })`).
54
+ *
55
+ * The pass only implements the host-wide shape. Probing structurally (instead of
56
+ * comparing versions) keeps this working when a host backports or renames the
57
+ * service, and lets an old host skip with one readable line instead of failing
58
+ * the same `list` call every sweep.
59
+ */
60
+ export function scheduleFlavor(schedule) {
61
+ if (!schedule || typeof schedule.create !== 'function' || typeof schedule.list !== 'function') return null
62
+ if (typeof schedule.edit === 'function') return 'global'
63
+ if (typeof schedule.delete === 'function') return 'session'
64
+ return null
65
+ }
66
+
44
67
  function pad2(value) {
45
68
  return String(value).padStart(2, '0')
46
69
  }
@@ -218,7 +241,8 @@ export async function runSalientWakePass(ctx, { now = new Date(), log = () => {}
218
241
 
219
242
  let schedule = null
220
243
  try { schedule = ctx?.get?.('schedule') || null } catch { schedule = null }
221
- if (!schedule || typeof schedule.create !== 'function' || typeof schedule.list !== 'function') {
244
+ const flavor = scheduleFlavor(schedule)
245
+ if (flavor === null) {
222
246
  if (!serviceWarned) {
223
247
  serviceWarned = true
224
248
  notify('salient wake is enabled but this host exposes no schedule service; skipping')
@@ -230,6 +254,18 @@ export async function runSalientWakePass(ctx, { now = new Date(), log = () => {}
230
254
  }
231
255
  return { skipped: 'service' }
232
256
  }
257
+ if (flavor === 'session') {
258
+ if (!sessionScopedWarned) {
259
+ sessionScopedWarned = true
260
+ notify('salient wake needs the host-wide schedule API (0.2.2+); this host exposes session-scoped reminders, skipping')
261
+ record({
262
+ kind: 'wake', level: 'warn', ok: false,
263
+ message: '日期唤醒需要宿主级 schedule API(0.2.2+);当前宿主只有会话级提醒,本轮跳过',
264
+ detail: { trigger: 'wake', stage: 'schedule-api' },
265
+ })
266
+ }
267
+ return { skipped: 'schedule-api' }
268
+ }
233
269
 
234
270
  const when = now instanceof Date ? now : new Date(now)
235
271
  if (!Number.isFinite(when.getTime())) return { skipped: 'time' }
package/lib/state.js CHANGED
@@ -99,11 +99,9 @@ export const DEFAULT_SETTINGS = {
99
99
  // These stay ordinary switches, and an existing saved choice is preserved.
100
100
  sleepConsolidation: true,
101
101
  // Group chat arrives in bursts, but a burst is seconds apart and the per-turn
102
- // timestamps already cover that. Three idle minutes is long enough that an
103
- // ordinary pause (reading a diff, thinking about the next question) is not
104
- // "gone", and short enough that a conversation which ended gets tidied in the
105
- // same sitting instead of waiting for a quiet hour that may never arrive.
106
- sleepAfterIdleMinutes: 3,
102
+ // timestamps already cover that. Two idle minutes still separates "reading a
103
+ // diff / thinking" from "gone", and keeps the per-run window small.
104
+ sleepAfterIdleMinutes: 2,
107
105
  // 主动记忆:分数门槛、饥饿阈值(空闲超过它无条件检查)、两种抑制冷却(分钟;整理冷却默认 0,
108
106
  // 薄证据的重复 fork 由评分拦截,只有用户显式配置才启用硬冷却)。
109
107
  activeMemoryMinScore: 0.8,
@@ -134,6 +132,19 @@ export const DEFAULT_SETTINGS = {
134
132
  salientWake: 'off',
135
133
  salientWakeHour: '09:00',
136
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',
137
148
  // A positive age marks cleanup candidates; deletion always needs a user action.
138
149
  purgeArchivedAfterDays: 0,
139
150
  }
@@ -377,7 +388,7 @@ export function updateSettings(patch) {
377
388
  activeMemoryMinScore: [0, 10], activeMemoryStarvationMinutes: [1, 1440],
378
389
  activeMemoryCooldownMinutes: [0, 10080], activeMemoryRecallCooldownMinutes: [0, 10080],
379
390
  }
380
- 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'] }
381
392
  for (const [key, value] of Object.entries(patch || {})) {
382
393
  if (!Object.hasOwn(DEFAULT_SETTINGS, key)) continue
383
394
  if (enums[key]) {
@@ -393,6 +404,35 @@ export function updateSettings(patch) {
393
404
  } else if (key === 'curatorModel') {
394
405
  if (value !== null && (typeof value !== 'string' || value.length > 200)) throw new Error('invalid curator model')
395
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()
396
436
  } else if (key === 'salientWakeHour') {
397
437
  // 定时唤醒的本地墙上时间。只收 HH:mm,不收 "9:00":宿主的 at 输入按 HH:mm[:ss]
398
438
  // 解释,少一位会被拒或读成别的时刻,宁可在设置页就拒绝。