@modusensus/dsh-mneme 0.8.3 → 0.8.5

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