@modusensus/dsh-mneme 0.8.3 → 0.8.4

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 (193) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +718 -636
  3. package/bin/cli.mjs +0 -0
  4. package/bin/dsh-mneme-mcp.mjs +502 -0
  5. package/cordis.patch.yml +21 -21
  6. package/lib/api-standalone.js +495 -316
  7. package/lib/api.js +1382 -1316
  8. package/lib/bootstrap.js +211 -0
  9. package/lib/client.js +4475 -4366
  10. package/lib/commands.js +95 -95
  11. package/lib/config.js +533 -510
  12. package/lib/dream/clustering.js +118 -118
  13. package/lib/dream/decisions.js +658 -658
  14. package/lib/dream/narratives.js +44 -0
  15. package/lib/dream/sleep.js +700 -700
  16. package/lib/dream.js +1319 -1216
  17. package/lib/embedding.js +177 -177
  18. package/lib/entities/extractor.js +249 -249
  19. package/lib/heat.js +142 -136
  20. package/lib/hot-memory.js +46 -46
  21. package/lib/index.js +515 -515
  22. package/lib/inject.js +299 -295
  23. package/lib/lang.js +202 -179
  24. package/lib/local-embedder.js +320 -320
  25. package/lib/mirror.js +198 -198
  26. package/lib/quality-filter.js +126 -126
  27. package/lib/recall-stats.js +103 -0
  28. package/lib/reranker.js +269 -269
  29. package/lib/runtime/adopt.js +176 -176
  30. package/lib/runtime/closure.js +172 -172
  31. package/lib/runtime/download.js +247 -247
  32. package/lib/runtime/layout.js +235 -235
  33. package/lib/runtime/loader.js +249 -249
  34. package/lib/runtime/model-fetch.js +361 -361
  35. package/lib/runtime/provision.js +237 -237
  36. package/lib/runtime/tarball.js +130 -130
  37. package/lib/runtime/verify.js +191 -191
  38. package/lib/scope.js +118 -118
  39. package/lib/search/adaptive.js +22 -22
  40. package/lib/search/bm25.js +96 -96
  41. package/lib/service.js +2171 -2087
  42. package/lib/settings.js +430 -420
  43. package/lib/store.js +2448 -2367
  44. package/lib/summarize.js +575 -449
  45. package/lib/tools.js +574 -574
  46. package/lib/vector-index.js +110 -110
  47. package/lib/version-check.js +122 -122
  48. package/package.json +109 -108
  49. package/runtime-manifest.json +596 -596
  50. package/scripts/benchmark-embed.js +201 -201
  51. package/scripts/benchmark-recall.js +199 -199
  52. package/scripts/benchmark-rerank.js +166 -166
  53. package/scripts/build-runtime-manifest.mjs +217 -217
  54. package/scripts/check-sync.js +42 -42
  55. package/scripts/e2e-dsh.js +220 -220
  56. package/scripts/mneme-runtime.mjs +277 -277
  57. package/scripts/stress-dsh.js +255 -255
  58. package/scripts/sync-lib.js +47 -47
  59. package/scripts/sync-test-badge.mjs +61 -61
  60. package/src/api-standalone.js +495 -316
  61. package/src/api.js +1382 -1316
  62. package/src/bootstrap.js +211 -0
  63. package/src/commands.js +95 -95
  64. package/src/config.js +533 -510
  65. package/src/dream/clustering.js +118 -118
  66. package/src/dream/decisions.js +658 -658
  67. package/src/dream/narratives.js +44 -0
  68. package/src/dream/sleep.js +700 -700
  69. package/src/dream.js +1319 -1216
  70. package/src/embedding.js +177 -177
  71. package/src/entities/extractor.js +249 -249
  72. package/src/heat.js +142 -136
  73. package/src/hot-memory.js +46 -46
  74. package/src/index.js +515 -515
  75. package/src/inject.js +299 -295
  76. package/src/lang.js +202 -179
  77. package/src/local-embedder.js +320 -320
  78. package/src/mirror.js +198 -198
  79. package/src/quality-filter.js +126 -126
  80. package/src/recall-stats.js +103 -0
  81. package/src/reranker.js +269 -269
  82. package/src/runtime/adopt.js +176 -176
  83. package/src/runtime/closure.js +172 -172
  84. package/src/runtime/download.js +247 -247
  85. package/src/runtime/layout.js +235 -235
  86. package/src/runtime/loader.js +249 -249
  87. package/src/runtime/model-fetch.js +361 -361
  88. package/src/runtime/provision.js +237 -237
  89. package/src/runtime/tarball.js +130 -130
  90. package/src/runtime/verify.js +191 -191
  91. package/src/scope.js +118 -118
  92. package/src/search/adaptive.js +22 -22
  93. package/src/search/bm25.js +96 -96
  94. package/src/service.js +2171 -2087
  95. package/src/settings.js +430 -420
  96. package/src/store.js +2448 -2367
  97. package/src/summarize.js +575 -449
  98. package/src/tools.js +574 -574
  99. package/src/vector-index.js +110 -110
  100. package/src/version-check.js +122 -122
  101. package/test/api-routes-gaps.test.js +218 -218
  102. package/test/api.test.js +1578 -1482
  103. package/test/audit.test.js +448 -448
  104. package/test/benchmark.test.js +94 -94
  105. package/test/bootstrap.test.js +220 -0
  106. package/test/client.test.js +799 -736
  107. package/test/clustering.test.js +100 -100
  108. package/test/commands.test.js +106 -106
  109. package/test/config.test.js +66 -66
  110. package/test/conflict-freeze.test.js +300 -300
  111. package/test/dream-archive-guardrail.test.js +116 -116
  112. package/test/dream-candidate-hybrid.test.js +281 -281
  113. package/test/dream-coverage-degrade.test.js +86 -86
  114. package/test/dream.test.js +1257 -1254
  115. package/test/embedding-ready.test.js +196 -196
  116. package/test/entities.test.js +547 -547
  117. package/test/entity-recall.test.js +179 -0
  118. package/test/epistemic.test.js +298 -298
  119. package/test/fnew-0112.test.js +311 -311
  120. package/test/fnew-03.test.js +422 -422
  121. package/test/graph-api.test.js +175 -175
  122. package/test/heat.test.js +175 -148
  123. package/test/helpers/dream-mock.js +82 -82
  124. package/test/helpers/peer-worker.mjs +25 -25
  125. package/test/helpers/runtime-source.js +60 -60
  126. package/test/helpers/tar-builder.js +80 -80
  127. package/test/hot-memory.test.js +145 -145
  128. package/test/inject-content-cap.test.js +89 -0
  129. package/test/inject-first-round-bm25.test.js +89 -89
  130. package/test/inject-heat.test.js +61 -0
  131. package/test/inject-rotation.test.js +161 -161
  132. package/test/inject.test.js +249 -249
  133. package/test/lang.test.js +87 -87
  134. package/test/lib-smoke.test.js +96 -96
  135. package/test/llm-audit.test.js +309 -309
  136. package/test/llm-message-source.test.js +177 -177
  137. package/test/local-embedder.test.js +249 -249
  138. package/test/mcp-stdio.test.js +385 -0
  139. package/test/mirror-dirty.test.js +424 -424
  140. package/test/mirror-edit-digest.test.js +187 -187
  141. package/test/mirror-generation.test.js +499 -499
  142. package/test/mirror.test.js +249 -249
  143. package/test/narrative-bars.test.js +162 -0
  144. package/test/peer-blockers.test.js +193 -193
  145. package/test/policy-epoch.test.js +259 -259
  146. package/test/quality-filter.test.js +186 -186
  147. package/test/reasoning-effort.test.js +746 -746
  148. package/test/recall-evals.test.js +235 -235
  149. package/test/recall-layer.test.js +326 -326
  150. package/test/recall-stats.test.js +117 -0
  151. package/test/receipt-chain.test.js +451 -451
  152. package/test/reflection.test.js +226 -226
  153. package/test/reindex-backfill.test.js +62 -62
  154. package/test/reranker-single-logit.test.js +73 -73
  155. package/test/reranker.test.js +197 -197
  156. package/test/resident-status.test.js +83 -0
  157. package/test/runtime-adopt.test.js +206 -206
  158. package/test/runtime-cli.test.js +89 -89
  159. package/test/runtime-closure.test.js +193 -193
  160. package/test/runtime-download.test.js +302 -302
  161. package/test/runtime-layout.test.js +163 -163
  162. package/test/runtime-loader.test.js +237 -237
  163. package/test/runtime-manifest.test.js +158 -158
  164. package/test/runtime-model-fetch.test.js +348 -348
  165. package/test/runtime-provision.test.js +101 -101
  166. package/test/runtime-tarball.test.js +81 -81
  167. package/test/runtime-verify.test.js +214 -214
  168. package/test/scope-candidates.test.js +239 -239
  169. package/test/scope-explicit.test.js +452 -452
  170. package/test/scope-retrieval.test.js +197 -197
  171. package/test/scope-storage.test.js +255 -255
  172. package/test/scope-strict.test.js +231 -231
  173. package/test/search-fusion.test.js +90 -90
  174. package/test/semantic.test.js +124 -124
  175. package/test/service-search.test.js +174 -174
  176. package/test/service.test.js +405 -405
  177. package/test/settings.test.js +261 -261
  178. package/test/skip-invalid-restore.test.js +262 -262
  179. package/test/sleep-action-set.test.js +422 -422
  180. package/test/sleep-heat.test.js +126 -125
  181. package/test/sleep-scheduler-rearm.test.js +89 -89
  182. package/test/sleep.test.js +373 -373
  183. package/test/standalone-api.test.js +544 -359
  184. package/test/store-vector-cache.test.js +98 -98
  185. package/test/store.test.js +383 -383
  186. package/test/stress.test.js +209 -209
  187. package/test/summarize.test.js +884 -575
  188. package/test/tools-memory-get-schema.test.js +65 -65
  189. package/test/tools.test.js +341 -341
  190. package/test/updated-at-semantics.test.js +113 -113
  191. package/test/vector-index.test.js +221 -221
  192. package/test/version-check.test.js +152 -152
  193. package/test/webServer-optional.test.js +82 -82
package/lib/settings.js CHANGED
@@ -1,420 +1,430 @@
1
- // User-configurable settings: profile (user self-description), rules (behavior
2
- // rules the agent must follow), and custom slash commands. Stored in the same
3
- // SQLite database via dedicated tables, isolated from the memories store.
4
- import { randomUUID } from "node:crypto";
5
-
6
- const SCHEMA = `
7
- CREATE TABLE IF NOT EXISTS user_settings (
8
- key TEXT PRIMARY KEY,
9
- value TEXT NOT NULL
10
- );
11
- CREATE TABLE IF NOT EXISTS custom_commands (
12
- id TEXT PRIMARY KEY,
13
- name TEXT NOT NULL UNIQUE,
14
- description TEXT NOT NULL DEFAULT '',
15
- instruction TEXT NOT NULL,
16
- created_at TEXT NOT NULL,
17
- updated_at TEXT NOT NULL
18
- );
19
- `;
20
-
21
- // DSH command names must match this (lowercase, start with a letter).
22
- const COMMAND_NAME = /^[a-z][a-z0-9_-]*$/;
23
-
24
- /** Parse a JSON array out of a stored string, tolerant of corruption. */
25
- function parseList(raw) {
26
- try {
27
- const value = JSON.parse(raw);
28
- return Array.isArray(value) ? value : [];
29
- } catch {
30
- return [];
31
- }
32
- }
33
-
34
- // --- feature flags(功能开关)白名单 -----------------------------------------
35
- // 面板可逐项开关的后端能力。设计约束:
36
- // 1. 键名与类型必须和 config.js schema 同名同型,这份白名单是唯一校验源
37
- // (api.js 复用它计算 effective),schema 增删能力键时要同步改这里。
38
- // 2. 持久化(kv "feature_flags")只落白名单键;读到未知键、类型损坏或越界的
39
- // 值一律丢弃而不是报错——kv 会残留旧版本写入的键,读路径必须向前兼容。
40
- // 3. 写入是逐键校验的合并写:未知键/类型/范围不符抛 TypeError(消息含键名,
41
- // 供 API 透传给前端定位),校验不通过不落库,坏值永远进不了 kv。
42
- const FEATURE_FLAG_BOOLEANS = [
43
- "autoInject",
44
- "autoSummarize",
45
- "hotMemoryEnabled",
46
- "entityExtractionEnabled",
47
- "codingRetrospect",
48
- "autoDream",
49
- "sleepModeEnabled",
50
- "heatEnabled",
51
- "hybridInject",
52
- "selectiveInjectEnabled",
53
- "searchSemanticDedup",
54
- "rerankEnabled",
55
- "resilientModelDownload",
56
- "adaptiveThresholdEnabled",
57
- "reflectionUpdateEnabled",
58
- "reflectionFailureTracking",
59
- "bm25SearchEnabled",
60
- "conflictFreezeEnabled",
61
- "trustEpistemicWeighting",
62
- // Plan #2: attach per-source {keyword, vector, bm25, final} signals to each
63
- // search result for transparency/debugging. Default off, purely decorative.
64
- "signalTransparency",
65
- // Issue #89:宽容校验回归(默认开)+ 跨类型合并显式放宽(默认关)。
66
- "dreamSkipInvalid",
67
- "allowCrossTypeMerge",
68
- // Issue #17(v0.8.0 A1):scope 隔离存储层总开关。开启后写入标注
69
- // agent_scope/workspace_scope、去重键扩展(含 sensitivity);检索侧过滤在
70
- // A2/A3。默认关=行为与 A1 前逐字节一致。
71
- "scopeEnabled",
72
- // Issue #17(v0.8.0 A3):strictScope 硬过滤——他 scope 完全不可见(关闭时
73
- // 为 A2 软隔离:降权保留可见)。
74
- "strictScope",
75
- // 嵌套对象开关:config.js 里是 memoryQualityFilter / llmAudit 对象的 enabled
76
- // 子字段。kv 按点号键平铺存("memoryQualityFilter.enabled": false),index.js
77
- // 合并时展开回嵌套对象,api.js 的 effective 从对象子字段取值。
78
- "memoryQualityFilter.enabled",
79
- "llmAudit.enabled"
80
- ];
81
- // 整数开关的闭区间,与 config.js 里 z.natural().min().max() 对齐。
82
- const FEATURE_FLAG_INT_RANGES = {
83
- distillRateLimitIntervalMs: [0, 60000],
84
- distillRateLimitRetries: [0, 10],
85
- distillRateLimitBaseDelayMs: [100, 60000],
86
- distillMaxChars: [1000, 200000],
87
- codingBoostFactor: [1, 5],
88
- dreamMinIntervalMinutes: [0, 10080],
89
- dreamMaxTokens: [256, 131072],
90
- // Issue #127:autoSummarize 节流三键(0 = 零行为变化,等同现状)。
91
- summarizeMinIntervalMinutes: [0, 10080],
92
- summarizeMaxEntriesPerRun: [0, 50],
93
- summarizeDedupeWindowHours: [0, 168],
94
- // Issue #125:hybrid 候选量上限(0 = 复用 dreamMaxSnapshotSize)。
95
- dreamCandidateMax: [0, 5000]
96
- };
97
- // 浮点开关的闭区间(与 config.js 的 z.number().min().max() 对齐)。与整数开关
98
- // 分开:面板的整数控件要求 Number.isInteger,而余弦相似度阈值必须允许小数。
99
- const FEATURE_FLAG_NUMBER_RANGES = {
100
- // Issue #127:vector 去重档的并入阈值。
101
- summarizeDedupeMinSim: [0.5, 0.99],
102
- // Issue #125:hybrid 判"高相似"的阈值。
103
- dreamCandidateMinSim: [0.5, 0.99]
104
- };
105
- // 自由字符串开关(与 config.js 的 z.string() 同名同型):trim 后 ≤200 字符,
106
- // 空串合法(= 跟随主对话模型/默认路径,面板显示 placeholder)。
107
- const FEATURE_FLAG_STRINGS = [
108
- "dreamProvider",
109
- "dreamModel",
110
- // 睡眠侧专用路由(sleep.js 的 config-first 第三层):面板下拉随
111
- // /llm-providers 端点一起提供,留空 = 用巩固模型或当前模型。
112
- "sleepProvider",
113
- "sleepModel",
114
- // 实体抽取侧专用路由(issue #109):provider/model 显式指定,
115
- // 留空 = 用当前默认模型。
116
- "entityExtractionProvider",
117
- "entityExtractionModel",
118
- "localEmbedModel",
119
- "ollamaModel"
120
- ];
121
- // URL 字符串开关:trim 后必须为空或合法 http/https URL(new URL() 校验协议,
122
- // 拒绝其余协议——这是 SSRF 防线的一部分)。
123
- const FEATURE_FLAG_URLS = ["ollamaBaseUrl"];
124
- // 枚举开关(与 config.js 的 z.union(z.const(...)) 对齐):仅允许列出的值。
125
- const FEATURE_FLAG_ENUMS = {
126
- embedProvider: ["openai", "local", "ollama"],
127
- // Plan #1: recall fusion recipe. blend = legacy (default); rrf / minmax are
128
- // rank/scale-aware alternatives selected by the panel.
129
- recallFusion: ["blend", "rrf", "minmax"],
130
- // 实体抽取思考强度(issue #109):与 dreamReasoningEffort 枚举对齐。
131
- entityExtractionReasoning: ["low", "medium", "high", "none"],
132
- // Issue #127:落库前去重档位(off 默认,等同现状)。
133
- summarizeDedupeMode: ["off", "title", "vector"],
134
- // Issue #126:sleep 冲突阶段的动作集(conflict 默认 = 现状;full = 六分支)。
135
- sleepActionSet: ["conflict", "full"],
136
- // Issue #125:dream 候选集构造方式(window 默认 = 现状;hybrid 并入向量组)。
137
- dreamCandidateMode: ["window", "hybrid"]
138
- };
139
- const FEATURE_FLAG_STRING_MAX = 200;
140
-
141
- // 供 api.js 复用同一份白名单(effective 只在白名单键上计算)。
142
- export const FEATURE_FLAG_SPEC = {
143
- booleans: FEATURE_FLAG_BOOLEANS,
144
- ints: FEATURE_FLAG_INT_RANGES,
145
- numbers: FEATURE_FLAG_NUMBER_RANGES,
146
- strings: FEATURE_FLAG_STRINGS,
147
- urls: FEATURE_FLAG_URLS,
148
- enums: FEATURE_FLAG_ENUMS
149
- };
150
-
151
- /** ollamaBaseUrl 的协议白名单:只接受 http/https(SSRF 防线的一部分)。 */
152
- function isHttpUrl(value) {
153
- try {
154
- const protocol = new URL(value).protocol;
155
- return protocol === "http:" || protocol === "https:";
156
- } catch {
157
- return false;
158
- }
159
- }
160
-
161
- /** 校验单个开关值;不合法抛 TypeError(消息含键名)。 */
162
- function validateFlag(key, value) {
163
- if (FEATURE_FLAG_BOOLEANS.includes(key)) {
164
- if (typeof value !== "boolean") {
165
- throw new TypeError(`feature flag "${key}" must be a boolean`);
166
- }
167
- return value;
168
- }
169
- const range = FEATURE_FLAG_INT_RANGES[key];
170
- if (range) {
171
- const [min, max] = range;
172
- if (!Number.isInteger(value) || value < min || value > max) {
173
- throw new TypeError(`feature flag "${key}" must be an integer in [${min}, ${max}]`);
174
- }
175
- return value;
176
- }
177
- const numRange = FEATURE_FLAG_NUMBER_RANGES[key];
178
- if (numRange) {
179
- const [min, max] = numRange;
180
- if (typeof value !== "number" || !Number.isFinite(value) || value < min || value > max) {
181
- throw new TypeError(`feature flag "${key}" must be a number in [${min}, ${max}]`);
182
- }
183
- return value;
184
- }
185
- if (FEATURE_FLAG_STRINGS.includes(key)) {
186
- if (typeof value !== "string") {
187
- throw new TypeError(`feature flag "${key}" must be a string`);
188
- }
189
- const trimmed = value.trim();
190
- if (trimmed.length > FEATURE_FLAG_STRING_MAX) {
191
- throw new TypeError(`feature flag "${key}" must be at most ${FEATURE_FLAG_STRING_MAX} characters`);
192
- }
193
- return trimmed; // 空串合法 = 跟随默认
194
- }
195
- if (FEATURE_FLAG_URLS.includes(key)) {
196
- if (typeof value !== "string") {
197
- throw new TypeError(`feature flag "${key}" must be a string`);
198
- }
199
- const trimmed = value.trim();
200
- if (trimmed && !isHttpUrl(trimmed)) {
201
- throw new TypeError(`feature flag "${key}" must be empty or a valid http(s) URL`);
202
- }
203
- return trimmed; // 空串合法 = 跟随默认
204
- }
205
- const allowed = FEATURE_FLAG_ENUMS[key];
206
- if (allowed) {
207
- if (typeof value !== "string" || !allowed.includes(value)) {
208
- throw new TypeError(`feature flag "${key}" must be one of: ${allowed.join(", ")}`);
209
- }
210
- return value;
211
- }
212
- throw new TypeError(`unknown feature flag "${key}"`);
213
- }
214
-
215
- /** 清洗已存的 feature_flags 对象:只保留白名单键,类型/范围损坏的键丢弃。 */
216
- function sanitizeFlags(raw) {
217
- const out = {};
218
- if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return out;
219
- for (const key of FEATURE_FLAG_BOOLEANS) {
220
- if (typeof raw[key] === "boolean") out[key] = raw[key];
221
- }
222
- for (const [key, [min, max]] of Object.entries(FEATURE_FLAG_INT_RANGES)) {
223
- if (Number.isInteger(raw[key]) && raw[key] >= min && raw[key] <= max) out[key] = raw[key];
224
- }
225
- for (const [key, [min, max]] of Object.entries(FEATURE_FLAG_NUMBER_RANGES)) {
226
- if (typeof raw[key] === "number" && Number.isFinite(raw[key]) && raw[key] >= min && raw[key] <= max) {
227
- out[key] = raw[key];
228
- }
229
- }
230
- for (const key of FEATURE_FLAG_STRINGS) {
231
- if (typeof raw[key] === "string" && raw[key].trim().length <= FEATURE_FLAG_STRING_MAX) {
232
- out[key] = raw[key].trim();
233
- }
234
- }
235
- for (const key of FEATURE_FLAG_URLS) {
236
- if (typeof raw[key] === "string") {
237
- const trimmed = raw[key].trim();
238
- if (!trimmed || isHttpUrl(trimmed)) out[key] = trimmed;
239
- }
240
- }
241
- for (const [key, allowed] of Object.entries(FEATURE_FLAG_ENUMS)) {
242
- if (allowed.includes(raw[key])) out[key] = raw[key];
243
- }
244
- return out;
245
- }
246
-
247
- export function createSettings(db) {
248
- db.exec(SCHEMA);
249
-
250
- function getSetting(key) {
251
- const row = db.prepare("SELECT value FROM user_settings WHERE key = ?").get(key);
252
- return row?.value ?? undefined;
253
- }
254
-
255
- function setSetting(key, value) {
256
- db.prepare(
257
- `INSERT INTO user_settings (key, value) VALUES (?, ?)
258
- ON CONFLICT(key) DO UPDATE SET value = excluded.value`
259
- ).run(key, value);
260
- }
261
-
262
- function toCommand(row) {
263
- if (!row) return undefined;
264
- return {
265
- id: row.id,
266
- name: row.name,
267
- description: row.description,
268
- instruction: row.instruction,
269
- created_at: row.created_at,
270
- updated_at: row.updated_at
271
- };
272
- }
273
-
274
- return {
275
- /** The user's self-description (free text) or "" when unset. */
276
- getProfile() {
277
- return getSetting("profile") ?? "";
278
- },
279
- setProfile(text) {
280
- setSetting("profile", String(text ?? ""));
281
- },
282
-
283
- /** Behavior rules as an array of strings. */
284
- getRules() {
285
- return parseList(getSetting("rules") ?? "[]").filter((r) => typeof r === "string");
286
- },
287
- setRules(rules) {
288
- const list = Array.isArray(rules) ? rules.filter((r) => typeof r === "string") : [];
289
- setSetting("rules", JSON.stringify(list));
290
- },
291
-
292
- /** All custom commands, sorted by name. */
293
- listCommands() {
294
- const rows = db.prepare("SELECT * FROM custom_commands ORDER BY name ASC").all();
295
- return rows.map(toCommand);
296
- },
297
-
298
- /**
299
- * Add or replace a custom command by name.
300
- * @returns the stored command.
301
- * @throws when name is invalid or does not match DSH's command-name grammar.
302
- */
303
- addCommand({ name, description = "", instruction }) {
304
- const cmdName = String(name ?? "").trim();
305
- if (!COMMAND_NAME.test(cmdName)) {
306
- throw new Error(`invalid command name "${cmdName}": must match /^[a-z][a-z0-9_-]*$/`);
307
- }
308
- if (typeof instruction !== "string" || !instruction.trim()) {
309
- throw new Error("command instruction must be a non-empty string");
310
- }
311
- const now = new Date().toISOString();
312
- const existing = db.prepare("SELECT id FROM custom_commands WHERE name = ?").get(cmdName);
313
- if (existing) {
314
- db.prepare(
315
- "UPDATE custom_commands SET description = ?, instruction = ?, updated_at = ? WHERE id = ?"
316
- ).run(String(description ?? ""), instruction, now, existing.id);
317
- return toCommand(db.prepare("SELECT * FROM custom_commands WHERE id = ?").get(existing.id));
318
- }
319
- const id = randomUUID();
320
- db.prepare(
321
- `INSERT INTO custom_commands (id, name, description, instruction, created_at, updated_at)
322
- VALUES (?, ?, ?, ?, ?, ?)`
323
- ).run(id, cmdName, String(description ?? ""), instruction, now, now);
324
- return toCommand(db.prepare("SELECT * FROM custom_commands WHERE id = ?").get(id));
325
- },
326
-
327
- /** Remove a custom command by id; returns true when removed. */
328
- removeCommand(id) {
329
- const result = db.prepare("DELETE FROM custom_commands WHERE id = ?").run(id);
330
- return result.changes > 0;
331
- },
332
-
333
- /** Vector-search provider config (OpenAI-compatible embeddings endpoint). */
334
- getVectorConfig() {
335
- const raw = getSetting("vector");
336
- if (!raw) return undefined;
337
- try {
338
- const cfg = JSON.parse(raw);
339
- return typeof cfg === "object" && cfg !== null ? cfg : undefined;
340
- } catch {
341
- return undefined;
342
- }
343
- },
344
- setVectorConfig({ enabled, baseUrl, apiKey, model }) {
345
- const cfg = {
346
- enabled: enabled === true || enabled === 1,
347
- baseUrl: String(baseUrl ?? "").trim().replace(/\/+$/, ""),
348
- apiKey: String(apiKey ?? "").trim(),
349
- model: String(model ?? "").trim()
350
- };
351
- setSetting("vector", JSON.stringify(cfg));
352
- return cfg;
353
- },
354
-
355
- /**
356
- * Standalone external API settings (kv "external_api"): {enabled, port,
357
- * token}. The Bearer token is auto-generated on first boot and persisted
358
- * here. Partial writes preserve the keys they don't mention.
359
- */
360
- getExternalApi() {
361
- const raw = getSetting("external_api");
362
- if (!raw) return undefined;
363
- try {
364
- const cfg = JSON.parse(raw);
365
- return typeof cfg === "object" && cfg !== null ? cfg : undefined;
366
- } catch {
367
- return undefined;
368
- }
369
- },
370
- setExternalApi(patch = {}) {
371
- const prev = this.getExternalApi() ?? {};
372
- const port = Number(patch.port ?? prev.port);
373
- const host = typeof patch.host === "string" && patch.host.trim() ? patch.host.trim() : (prev.host ?? "127.0.0.1");
374
- const cfg = {
375
- enabled: patch.enabled !== undefined ? patch.enabled === true : prev.enabled === true,
376
- port: Number.isInteger(port) && port > 0 ? port : 8790,
377
- host,
378
- token: String(patch.token ?? prev.token ?? "")
379
- };
380
- setSetting("external_api", JSON.stringify(cfg));
381
- return cfg;
382
- },
383
-
384
- /**
385
- * Web panel mode (kv "panel_mode"): "light" (low-resource preset) or
386
- * "standard" (full feature set). Unset reads as "standard".
387
- */
388
- getPanelMode() {
389
- return getSetting("panel_mode") === "light" ? "light" : "standard";
390
- },
391
- setPanelMode(mode) {
392
- setSetting("panel_mode", mode === "light" ? "light" : "standard");
393
- },
394
-
395
- /**
396
- * Feature flags(kv "feature_flags"):面板对后端能力的显式覆盖。读取只
397
- * 返回白名单内的合法键(默认 {}),写入是逐键校验后的合并持久化。
398
- */
399
- getFeatureFlags() {
400
- const raw = getSetting("feature_flags");
401
- if (!raw) return {};
402
- try {
403
- return sanitizeFlags(JSON.parse(raw));
404
- } catch {
405
- return {};
406
- }
407
- },
408
- setFeatureFlags(patch) {
409
- if (typeof patch !== "object" || patch === null || Array.isArray(patch)) {
410
- throw new TypeError("feature flags patch must be a plain object");
411
- }
412
- const merged = this.getFeatureFlags();
413
- for (const [key, value] of Object.entries(patch)) {
414
- merged[key] = validateFlag(key, value);
415
- }
416
- setSetting("feature_flags", JSON.stringify(merged));
417
- return merged;
418
- }
419
- };
420
- }
1
+ // User-configurable settings: profile (user self-description), rules (behavior
2
+ // rules the agent must follow), and custom slash commands. Stored in the same
3
+ // SQLite database via dedicated tables, isolated from the memories store.
4
+ import { randomUUID } from "node:crypto";
5
+
6
+ const SCHEMA = `
7
+ CREATE TABLE IF NOT EXISTS user_settings (
8
+ key TEXT PRIMARY KEY,
9
+ value TEXT NOT NULL
10
+ );
11
+ CREATE TABLE IF NOT EXISTS custom_commands (
12
+ id TEXT PRIMARY KEY,
13
+ name TEXT NOT NULL UNIQUE,
14
+ description TEXT NOT NULL DEFAULT '',
15
+ instruction TEXT NOT NULL,
16
+ created_at TEXT NOT NULL,
17
+ updated_at TEXT NOT NULL
18
+ );
19
+ `;
20
+
21
+ // DSH command names must match this (lowercase, start with a letter).
22
+ const COMMAND_NAME = /^[a-z][a-z0-9_-]*$/;
23
+
24
+ /** Parse a JSON array out of a stored string, tolerant of corruption. */
25
+ function parseList(raw) {
26
+ try {
27
+ const value = JSON.parse(raw);
28
+ return Array.isArray(value) ? value : [];
29
+ } catch {
30
+ return [];
31
+ }
32
+ }
33
+
34
+ // --- feature flags(功能开关)白名单 -----------------------------------------
35
+ // 面板可逐项开关的后端能力。设计约束:
36
+ // 1. 键名与类型必须和 config.js schema 同名同型,这份白名单是唯一校验源
37
+ // (api.js 复用它计算 effective),schema 增删能力键时要同步改这里。
38
+ // 2. 持久化(kv "feature_flags")只落白名单键;读到未知键、类型损坏或越界的
39
+ // 值一律丢弃而不是报错——kv 会残留旧版本写入的键,读路径必须向前兼容。
40
+ // 3. 写入是逐键校验的合并写:未知键/类型/范围不符抛 TypeError(消息含键名,
41
+ // 供 API 透传给前端定位),校验不通过不落库,坏值永远进不了 kv。
42
+ const FEATURE_FLAG_BOOLEANS = [
43
+ "autoInject",
44
+ "autoSummarize",
45
+ "hotMemoryEnabled",
46
+ "entityExtractionEnabled",
47
+ // Issue #219:图召回轴——查询命中实体名时把挂联记忆并入检索融合池
48
+ // (默认关;依赖实体抽取产出,lightMode 强制关闭)。
49
+ "entityRecallEnabled",
50
+ // Issue #164:叙述条——dream 期间按 tag 主题簇合成叙述落库(source=
51
+ // narrative,evidence 回链簇内记忆;按需检索不常驻注入;默认关)。
52
+ "dreamNarrativeEnabled",
53
+ "codingRetrospect",
54
+ "autoDream",
55
+ "sleepModeEnabled",
56
+ "heatEnabled",
57
+ "hybridInject",
58
+ "selectiveInjectEnabled",
59
+ "searchSemanticDedup",
60
+ "rerankEnabled",
61
+ "resilientModelDownload",
62
+ "adaptiveThresholdEnabled",
63
+ "reflectionUpdateEnabled",
64
+ "reflectionFailureTracking",
65
+ "bm25SearchEnabled",
66
+ "conflictFreezeEnabled",
67
+ "trustEpistemicWeighting",
68
+ // Plan #2: attach per-source {keyword, vector, bm25, final} signals to each
69
+ // search result for transparency/debugging. Default off, purely decorative.
70
+ "signalTransparency",
71
+ // Issue #89:宽容校验回归(默认开)+ 跨类型合并显式放宽(默认关)。
72
+ "dreamSkipInvalid",
73
+ "allowCrossTypeMerge",
74
+ // Issue #17(v0.8.0 A1):scope 隔离存储层总开关。开启后写入标注
75
+ // agent_scope/workspace_scope、去重键扩展(含 sensitivity);检索侧过滤在
76
+ // A2/A3。默认关=行为与 A1 前逐字节一致。
77
+ "scopeEnabled",
78
+ // Issue #17(v0.8.0 A3):strictScope 硬过滤——他 scope 完全不可见(关闭时
79
+ // 为 A2 软隔离:降权保留可见)。
80
+ "strictScope",
81
+ // 嵌套对象开关:config.js 里是 memoryQualityFilter / llmAudit 对象的 enabled
82
+ // 子字段。kv 按点号键平铺存("memoryQualityFilter.enabled": false),index.js
83
+ // 合并时展开回嵌套对象,api.js 的 effective 从对象子字段取值。
84
+ "memoryQualityFilter.enabled",
85
+ "llmAudit.enabled"
86
+ ];
87
+ // 整数开关的闭区间,与 config.js 里 z.natural().min().max() 对齐。
88
+ const FEATURE_FLAG_INT_RANGES = {
89
+ distillRateLimitIntervalMs: [0, 60000],
90
+ distillRateLimitRetries: [0, 10],
91
+ distillRateLimitBaseDelayMs: [100, 60000],
92
+ distillMaxChars: [1000, 200000],
93
+ codingBoostFactor: [1, 5],
94
+ dreamMinIntervalMinutes: [0, 10080],
95
+ dreamMaxTokens: [256, 131072],
96
+ // Issue #127:autoSummarize 节流三键(0 = 零行为变化,等同现状)。
97
+ summarizeMinIntervalMinutes: [0, 10080],
98
+ summarizeMaxEntriesPerRun: [0, 50],
99
+ summarizeDedupeWindowHours: [0, 168],
100
+ // Issue #125:hybrid 候选量上限(0 = 复用 dreamMaxSnapshotSize)。
101
+ dreamCandidateMax: [0, 5000],
102
+ // Issue #164①:注入单条正文截断上限(默认 300 = 既有行为)。
103
+ injectContentMaxChars: [60, 4000],
104
+ // Issue #164:叙述条成簇门槛(共享同一 tag 的记忆数下限)。
105
+ dreamNarrativeMinCluster: [2, 20]
106
+ };
107
+ // 浮点开关的闭区间(与 config.js 的 z.number().min().max() 对齐)。与整数开关
108
+ // 分开:面板的整数控件要求 Number.isInteger,而余弦相似度阈值必须允许小数。
109
+ const FEATURE_FLAG_NUMBER_RANGES = {
110
+ // Issue #127:vector 去重档的并入阈值。
111
+ summarizeDedupeMinSim: [0.5, 0.99],
112
+ // Issue #125:hybrid 判"高相似"的阈值。
113
+ dreamCandidateMinSim: [0.5, 0.99]
114
+ };
115
+ // 自由字符串开关(与 config.js 的 z.string() 同名同型):trim 后 ≤200 字符,
116
+ // 空串合法(= 跟随主对话模型/默认路径,面板显示 placeholder)。
117
+ const FEATURE_FLAG_STRINGS = [
118
+ "dreamProvider",
119
+ "dreamModel",
120
+ // 睡眠侧专用路由(sleep.js 的 config-first 第三层):面板下拉随
121
+ // /llm-providers 端点一起提供,留空 = 用巩固模型或当前模型。
122
+ "sleepProvider",
123
+ "sleepModel",
124
+ // 实体抽取侧专用路由(issue #109):provider/model 显式指定,
125
+ // 留空 = 用当前默认模型。
126
+ "entityExtractionProvider",
127
+ "entityExtractionModel",
128
+ "localEmbedModel",
129
+ "ollamaModel"
130
+ ];
131
+ // URL 字符串开关:trim 后必须为空或合法 http/https URL(new URL() 校验协议,
132
+ // 拒绝其余协议——这是 SSRF 防线的一部分)。
133
+ const FEATURE_FLAG_URLS = ["ollamaBaseUrl"];
134
+ // 枚举开关(与 config.js 的 z.union(z.const(...)) 对齐):仅允许列出的值。
135
+ const FEATURE_FLAG_ENUMS = {
136
+ embedProvider: ["openai", "local", "ollama"],
137
+ // Plan #1: recall fusion recipe. blend = legacy (default); rrf / minmax are
138
+ // rank/scale-aware alternatives selected by the panel.
139
+ recallFusion: ["blend", "rrf", "minmax"],
140
+ // 实体抽取思考强度(issue #109):与 dreamReasoningEffort 枚举对齐。
141
+ entityExtractionReasoning: ["low", "medium", "high", "none"],
142
+ // Issue #127:落库前去重档位(off 默认,等同现状)。
143
+ summarizeDedupeMode: ["off", "title", "vector"],
144
+ // Issue #126:sleep 冲突阶段的动作集(conflict 默认 = 现状;full = 六分支)。
145
+ sleepActionSet: ["conflict", "full"],
146
+ // Issue #125:dream 候选集构造方式(window 默认 = 现状;hybrid 并入向量组)。
147
+ dreamCandidateMode: ["window", "hybrid"]
148
+ };
149
+ const FEATURE_FLAG_STRING_MAX = 200;
150
+
151
+ // 供 api.js 复用同一份白名单(effective 只在白名单键上计算)。
152
+ export const FEATURE_FLAG_SPEC = {
153
+ booleans: FEATURE_FLAG_BOOLEANS,
154
+ ints: FEATURE_FLAG_INT_RANGES,
155
+ numbers: FEATURE_FLAG_NUMBER_RANGES,
156
+ strings: FEATURE_FLAG_STRINGS,
157
+ urls: FEATURE_FLAG_URLS,
158
+ enums: FEATURE_FLAG_ENUMS
159
+ };
160
+
161
+ /** ollamaBaseUrl 的协议白名单:只接受 http/https(SSRF 防线的一部分)。 */
162
+ function isHttpUrl(value) {
163
+ try {
164
+ const protocol = new URL(value).protocol;
165
+ return protocol === "http:" || protocol === "https:";
166
+ } catch {
167
+ return false;
168
+ }
169
+ }
170
+
171
+ /** 校验单个开关值;不合法抛 TypeError(消息含键名)。 */
172
+ function validateFlag(key, value) {
173
+ if (FEATURE_FLAG_BOOLEANS.includes(key)) {
174
+ if (typeof value !== "boolean") {
175
+ throw new TypeError(`feature flag "${key}" must be a boolean`);
176
+ }
177
+ return value;
178
+ }
179
+ const range = FEATURE_FLAG_INT_RANGES[key];
180
+ if (range) {
181
+ const [min, max] = range;
182
+ if (!Number.isInteger(value) || value < min || value > max) {
183
+ throw new TypeError(`feature flag "${key}" must be an integer in [${min}, ${max}]`);
184
+ }
185
+ return value;
186
+ }
187
+ const numRange = FEATURE_FLAG_NUMBER_RANGES[key];
188
+ if (numRange) {
189
+ const [min, max] = numRange;
190
+ if (typeof value !== "number" || !Number.isFinite(value) || value < min || value > max) {
191
+ throw new TypeError(`feature flag "${key}" must be a number in [${min}, ${max}]`);
192
+ }
193
+ return value;
194
+ }
195
+ if (FEATURE_FLAG_STRINGS.includes(key)) {
196
+ if (typeof value !== "string") {
197
+ throw new TypeError(`feature flag "${key}" must be a string`);
198
+ }
199
+ const trimmed = value.trim();
200
+ if (trimmed.length > FEATURE_FLAG_STRING_MAX) {
201
+ throw new TypeError(`feature flag "${key}" must be at most ${FEATURE_FLAG_STRING_MAX} characters`);
202
+ }
203
+ return trimmed; // 空串合法 = 跟随默认
204
+ }
205
+ if (FEATURE_FLAG_URLS.includes(key)) {
206
+ if (typeof value !== "string") {
207
+ throw new TypeError(`feature flag "${key}" must be a string`);
208
+ }
209
+ const trimmed = value.trim();
210
+ if (trimmed && !isHttpUrl(trimmed)) {
211
+ throw new TypeError(`feature flag "${key}" must be empty or a valid http(s) URL`);
212
+ }
213
+ return trimmed; // 空串合法 = 跟随默认
214
+ }
215
+ const allowed = FEATURE_FLAG_ENUMS[key];
216
+ if (allowed) {
217
+ if (typeof value !== "string" || !allowed.includes(value)) {
218
+ throw new TypeError(`feature flag "${key}" must be one of: ${allowed.join(", ")}`);
219
+ }
220
+ return value;
221
+ }
222
+ throw new TypeError(`unknown feature flag "${key}"`);
223
+ }
224
+
225
+ /** 清洗已存的 feature_flags 对象:只保留白名单键,类型/范围损坏的键丢弃。 */
226
+ function sanitizeFlags(raw) {
227
+ const out = {};
228
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return out;
229
+ for (const key of FEATURE_FLAG_BOOLEANS) {
230
+ if (typeof raw[key] === "boolean") out[key] = raw[key];
231
+ }
232
+ for (const [key, [min, max]] of Object.entries(FEATURE_FLAG_INT_RANGES)) {
233
+ if (Number.isInteger(raw[key]) && raw[key] >= min && raw[key] <= max) out[key] = raw[key];
234
+ }
235
+ for (const [key, [min, max]] of Object.entries(FEATURE_FLAG_NUMBER_RANGES)) {
236
+ if (typeof raw[key] === "number" && Number.isFinite(raw[key]) && raw[key] >= min && raw[key] <= max) {
237
+ out[key] = raw[key];
238
+ }
239
+ }
240
+ for (const key of FEATURE_FLAG_STRINGS) {
241
+ if (typeof raw[key] === "string" && raw[key].trim().length <= FEATURE_FLAG_STRING_MAX) {
242
+ out[key] = raw[key].trim();
243
+ }
244
+ }
245
+ for (const key of FEATURE_FLAG_URLS) {
246
+ if (typeof raw[key] === "string") {
247
+ const trimmed = raw[key].trim();
248
+ if (!trimmed || isHttpUrl(trimmed)) out[key] = trimmed;
249
+ }
250
+ }
251
+ for (const [key, allowed] of Object.entries(FEATURE_FLAG_ENUMS)) {
252
+ if (allowed.includes(raw[key])) out[key] = raw[key];
253
+ }
254
+ return out;
255
+ }
256
+
257
+ export function createSettings(db) {
258
+ db.exec(SCHEMA);
259
+
260
+ function getSetting(key) {
261
+ const row = db.prepare("SELECT value FROM user_settings WHERE key = ?").get(key);
262
+ return row?.value ?? undefined;
263
+ }
264
+
265
+ function setSetting(key, value) {
266
+ db.prepare(
267
+ `INSERT INTO user_settings (key, value) VALUES (?, ?)
268
+ ON CONFLICT(key) DO UPDATE SET value = excluded.value`
269
+ ).run(key, value);
270
+ }
271
+
272
+ function toCommand(row) {
273
+ if (!row) return undefined;
274
+ return {
275
+ id: row.id,
276
+ name: row.name,
277
+ description: row.description,
278
+ instruction: row.instruction,
279
+ created_at: row.created_at,
280
+ updated_at: row.updated_at
281
+ };
282
+ }
283
+
284
+ return {
285
+ /** The user's self-description (free text) or "" when unset. */
286
+ getProfile() {
287
+ return getSetting("profile") ?? "";
288
+ },
289
+ setProfile(text) {
290
+ setSetting("profile", String(text ?? ""));
291
+ },
292
+
293
+ /** Behavior rules as an array of strings. */
294
+ getRules() {
295
+ return parseList(getSetting("rules") ?? "[]").filter((r) => typeof r === "string");
296
+ },
297
+ setRules(rules) {
298
+ const list = Array.isArray(rules) ? rules.filter((r) => typeof r === "string") : [];
299
+ setSetting("rules", JSON.stringify(list));
300
+ },
301
+
302
+ /** All custom commands, sorted by name. */
303
+ listCommands() {
304
+ const rows = db.prepare("SELECT * FROM custom_commands ORDER BY name ASC").all();
305
+ return rows.map(toCommand);
306
+ },
307
+
308
+ /**
309
+ * Add or replace a custom command by name.
310
+ * @returns the stored command.
311
+ * @throws when name is invalid or does not match DSH's command-name grammar.
312
+ */
313
+ addCommand({ name, description = "", instruction }) {
314
+ const cmdName = String(name ?? "").trim();
315
+ if (!COMMAND_NAME.test(cmdName)) {
316
+ throw new Error(`invalid command name "${cmdName}": must match /^[a-z][a-z0-9_-]*$/`);
317
+ }
318
+ if (typeof instruction !== "string" || !instruction.trim()) {
319
+ throw new Error("command instruction must be a non-empty string");
320
+ }
321
+ const now = new Date().toISOString();
322
+ const existing = db.prepare("SELECT id FROM custom_commands WHERE name = ?").get(cmdName);
323
+ if (existing) {
324
+ db.prepare(
325
+ "UPDATE custom_commands SET description = ?, instruction = ?, updated_at = ? WHERE id = ?"
326
+ ).run(String(description ?? ""), instruction, now, existing.id);
327
+ return toCommand(db.prepare("SELECT * FROM custom_commands WHERE id = ?").get(existing.id));
328
+ }
329
+ const id = randomUUID();
330
+ db.prepare(
331
+ `INSERT INTO custom_commands (id, name, description, instruction, created_at, updated_at)
332
+ VALUES (?, ?, ?, ?, ?, ?)`
333
+ ).run(id, cmdName, String(description ?? ""), instruction, now, now);
334
+ return toCommand(db.prepare("SELECT * FROM custom_commands WHERE id = ?").get(id));
335
+ },
336
+
337
+ /** Remove a custom command by id; returns true when removed. */
338
+ removeCommand(id) {
339
+ const result = db.prepare("DELETE FROM custom_commands WHERE id = ?").run(id);
340
+ return result.changes > 0;
341
+ },
342
+
343
+ /** Vector-search provider config (OpenAI-compatible embeddings endpoint). */
344
+ getVectorConfig() {
345
+ const raw = getSetting("vector");
346
+ if (!raw) return undefined;
347
+ try {
348
+ const cfg = JSON.parse(raw);
349
+ return typeof cfg === "object" && cfg !== null ? cfg : undefined;
350
+ } catch {
351
+ return undefined;
352
+ }
353
+ },
354
+ setVectorConfig({ enabled, baseUrl, apiKey, model }) {
355
+ const cfg = {
356
+ enabled: enabled === true || enabled === 1,
357
+ baseUrl: String(baseUrl ?? "").trim().replace(/\/+$/, ""),
358
+ apiKey: String(apiKey ?? "").trim(),
359
+ model: String(model ?? "").trim()
360
+ };
361
+ setSetting("vector", JSON.stringify(cfg));
362
+ return cfg;
363
+ },
364
+
365
+ /**
366
+ * Standalone external API settings (kv "external_api"): {enabled, port,
367
+ * token}. The Bearer token is auto-generated on first boot and persisted
368
+ * here. Partial writes preserve the keys they don't mention.
369
+ */
370
+ getExternalApi() {
371
+ const raw = getSetting("external_api");
372
+ if (!raw) return undefined;
373
+ try {
374
+ const cfg = JSON.parse(raw);
375
+ return typeof cfg === "object" && cfg !== null ? cfg : undefined;
376
+ } catch {
377
+ return undefined;
378
+ }
379
+ },
380
+ setExternalApi(patch = {}) {
381
+ const prev = this.getExternalApi() ?? {};
382
+ const port = Number(patch.port ?? prev.port);
383
+ const host = typeof patch.host === "string" && patch.host.trim() ? patch.host.trim() : (prev.host ?? "127.0.0.1");
384
+ const cfg = {
385
+ enabled: patch.enabled !== undefined ? patch.enabled === true : prev.enabled === true,
386
+ port: Number.isInteger(port) && port > 0 ? port : 8790,
387
+ host,
388
+ token: String(patch.token ?? prev.token ?? "")
389
+ };
390
+ setSetting("external_api", JSON.stringify(cfg));
391
+ return cfg;
392
+ },
393
+
394
+ /**
395
+ * Web panel mode (kv "panel_mode"): "light" (low-resource preset) or
396
+ * "standard" (full feature set). Unset reads as "standard".
397
+ */
398
+ getPanelMode() {
399
+ return getSetting("panel_mode") === "light" ? "light" : "standard";
400
+ },
401
+ setPanelMode(mode) {
402
+ setSetting("panel_mode", mode === "light" ? "light" : "standard");
403
+ },
404
+
405
+ /**
406
+ * Feature flags(kv "feature_flags"):面板对后端能力的显式覆盖。读取只
407
+ * 返回白名单内的合法键(默认 {}),写入是逐键校验后的合并持久化。
408
+ */
409
+ getFeatureFlags() {
410
+ const raw = getSetting("feature_flags");
411
+ if (!raw) return {};
412
+ try {
413
+ return sanitizeFlags(JSON.parse(raw));
414
+ } catch {
415
+ return {};
416
+ }
417
+ },
418
+ setFeatureFlags(patch) {
419
+ if (typeof patch !== "object" || patch === null || Array.isArray(patch)) {
420
+ throw new TypeError("feature flags patch must be a plain object");
421
+ }
422
+ const merged = this.getFeatureFlags();
423
+ for (const [key, value] of Object.entries(patch)) {
424
+ merged[key] = validateFlag(key, value);
425
+ }
426
+ setSetting("feature_flags", JSON.stringify(merged));
427
+ return merged;
428
+ }
429
+ };
430
+ }