@modusensus/dsh-mneme 0.8.13 → 0.8.15

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 (271) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +655 -626
  3. package/assets/icon.svg +3 -3
  4. package/bin/cli.mjs +689 -689
  5. package/bin/dsh-mneme-mcp.mjs +510 -510
  6. package/bin/dsh-mneme-serve.mjs +151 -0
  7. package/cordis.patch.yml +21 -21
  8. package/docs/CONFIGURATION.md +263 -0
  9. package/docs/CONTINUITY.md +124 -0
  10. package/docs/DAEMON.md +46 -0
  11. package/docs/ENTITIES.md +245 -0
  12. package/docs/LOCAL_MODEL.md +222 -0
  13. package/docs/SEMANTIC.md +256 -0
  14. package/docs/SLEEP.md +164 -0
  15. package/docs/STORAGE.md +89 -0
  16. package/lib/api-standalone.js +673 -572
  17. package/lib/api.js +1437 -1433
  18. package/lib/bootstrap.js +211 -211
  19. package/lib/client.js +5444 -5295
  20. package/lib/commands.js +95 -95
  21. package/lib/config.js +880 -836
  22. package/lib/content-hash.js +54 -54
  23. package/lib/continuity.js +220 -220
  24. package/lib/document-index.js +94 -94
  25. package/lib/document.js +303 -303
  26. package/lib/dream/clustering.js +118 -118
  27. package/lib/dream/decisions.js +674 -674
  28. package/lib/dream/narratives.js +44 -44
  29. package/lib/dream/sleep.js +819 -819
  30. package/lib/dream.js +1501 -1501
  31. package/lib/embedding.js +177 -177
  32. package/lib/entities/extractor.js +252 -252
  33. package/lib/graph/anchoring.js +179 -179
  34. package/lib/guide.js +74 -74
  35. package/lib/heat.js +144 -144
  36. package/lib/hot-memory.js +46 -46
  37. package/lib/index.js +535 -671
  38. package/lib/inject.js +464 -450
  39. package/lib/lang.js +248 -229
  40. package/lib/local-embedder.js +358 -358
  41. package/lib/maintenance.js +142 -142
  42. package/lib/mirror.js +330 -330
  43. package/lib/organize.js +450 -450
  44. package/lib/peak-hours.js +117 -117
  45. package/lib/placement.js +13 -0
  46. package/lib/pre-inject-gate.js +340 -0
  47. package/lib/quality-filter.js +126 -126
  48. package/lib/recall-stats.js +175 -175
  49. package/lib/reranker.js +269 -269
  50. package/lib/runtime/adopt.js +176 -176
  51. package/lib/runtime/closure.js +172 -172
  52. package/lib/runtime/download.js +247 -247
  53. package/lib/runtime/layout.js +265 -265
  54. package/lib/runtime/loader.js +252 -252
  55. package/lib/runtime/model-fetch.js +361 -361
  56. package/lib/runtime/provision.js +237 -237
  57. package/lib/runtime/tarball.js +130 -130
  58. package/lib/runtime/verify.js +223 -204
  59. package/lib/scope.js +146 -146
  60. package/lib/search/adaptive.js +60 -60
  61. package/lib/search/bm25.js +96 -96
  62. package/lib/semantic.js +229 -0
  63. package/lib/sensitive-scan.js +209 -209
  64. package/lib/serve.js +215 -0
  65. package/lib/service.js +2663 -2596
  66. package/lib/settings.js +517 -509
  67. package/lib/store.js +3007 -3007
  68. package/lib/summarize.js +891 -856
  69. package/lib/tools.js +743 -737
  70. package/lib/vector-index.js +110 -110
  71. package/lib/version-check.js +122 -122
  72. package/lib/write-admission.js +402 -402
  73. package/locale/en.json +6 -6
  74. package/locale/zh.json +6 -6
  75. package/package.json +8 -4
  76. package/runtime-manifest.json +526 -526
  77. package/scripts/benchmark-embed.js +201 -201
  78. package/scripts/benchmark-recall.js +249 -249
  79. package/scripts/benchmark-rerank.js +166 -166
  80. package/scripts/build-runtime-manifest.mjs +224 -224
  81. package/scripts/changelog-prep.mjs +36 -0
  82. package/scripts/check-sync.js +42 -42
  83. package/scripts/e2e-dsh.js +220 -220
  84. package/scripts/mneme-runtime.mjs +277 -277
  85. package/scripts/stress-dsh.js +255 -255
  86. package/scripts/sync-lib.js +47 -47
  87. package/scripts/sync-test-badge.mjs +69 -69
  88. package/scripts/test-count-sync.mjs +44 -44
  89. package/src/api-standalone.js +673 -572
  90. package/src/api.js +1437 -1433
  91. package/src/bootstrap.js +211 -211
  92. package/src/commands.js +95 -95
  93. package/src/config.js +880 -836
  94. package/src/content-hash.js +54 -54
  95. package/src/continuity.js +220 -220
  96. package/src/document-index.js +94 -94
  97. package/src/document.js +303 -303
  98. package/src/dream/clustering.js +118 -118
  99. package/src/dream/decisions.js +674 -674
  100. package/src/dream/narratives.js +44 -44
  101. package/src/dream/sleep.js +819 -819
  102. package/src/dream.js +1501 -1501
  103. package/src/embedding.js +177 -177
  104. package/src/entities/extractor.js +252 -252
  105. package/src/graph/anchoring.js +179 -179
  106. package/src/guide.js +74 -74
  107. package/src/heat.js +144 -144
  108. package/src/hot-memory.js +46 -46
  109. package/src/index.js +535 -671
  110. package/src/inject.js +464 -450
  111. package/src/lang.js +248 -229
  112. package/src/local-embedder.js +358 -358
  113. package/src/maintenance.js +142 -142
  114. package/src/mirror.js +330 -330
  115. package/src/organize.js +450 -450
  116. package/src/peak-hours.js +117 -117
  117. package/src/placement.js +13 -0
  118. package/src/pre-inject-gate.js +340 -0
  119. package/src/quality-filter.js +126 -126
  120. package/src/recall-stats.js +175 -175
  121. package/src/reranker.js +269 -269
  122. package/src/runtime/adopt.js +176 -176
  123. package/src/runtime/closure.js +172 -172
  124. package/src/runtime/download.js +247 -247
  125. package/src/runtime/layout.js +265 -265
  126. package/src/runtime/loader.js +252 -252
  127. package/src/runtime/model-fetch.js +361 -361
  128. package/src/runtime/provision.js +237 -237
  129. package/src/runtime/tarball.js +130 -130
  130. package/src/runtime/verify.js +223 -204
  131. package/src/scope.js +146 -146
  132. package/src/search/adaptive.js +60 -60
  133. package/src/search/bm25.js +96 -96
  134. package/src/semantic.js +229 -0
  135. package/src/sensitive-scan.js +209 -209
  136. package/src/serve.js +215 -0
  137. package/src/service.js +2663 -2596
  138. package/src/settings.js +517 -509
  139. package/src/store.js +3007 -3007
  140. package/src/summarize.js +891 -856
  141. package/src/tools.js +743 -737
  142. package/src/vector-index.js +110 -110
  143. package/src/version-check.js +122 -122
  144. package/src/write-admission.js +402 -402
  145. package/test/adaptive-inject-budget.test.js +85 -85
  146. package/test/api-routes-gaps.test.js +218 -218
  147. package/test/api.test.js +1702 -1688
  148. package/test/audit.test.js +448 -448
  149. package/test/baseline-persist.test.js +248 -248
  150. package/test/benchmark.test.js +94 -94
  151. package/test/bootstrap.test.js +220 -220
  152. package/test/changelog-prep.test.js +60 -0
  153. package/test/client.test.js +1230 -1169
  154. package/test/clustering.test.js +100 -100
  155. package/test/commands.test.js +106 -106
  156. package/test/config.test.js +66 -66
  157. package/test/conflict-freeze.test.js +300 -300
  158. package/test/content-hash.test.js +204 -204
  159. package/test/continuity.test.js +333 -333
  160. package/test/document-dir.test.js +233 -233
  161. package/test/document.test.js +671 -671
  162. package/test/dream-archive-guardrail.test.js +116 -116
  163. package/test/dream-candidate-hybrid.test.js +281 -281
  164. package/test/dream-coverage-degrade.test.js +86 -86
  165. package/test/dream-failure-backoff.test.js +173 -173
  166. package/test/dream-peak-hours.test.js +194 -194
  167. package/test/dream.test.js +1385 -1383
  168. package/test/embedding-ready.test.js +196 -196
  169. package/test/entities.test.js +627 -547
  170. package/test/entity-recall.test.js +179 -179
  171. package/test/epistemic.test.js +325 -325
  172. package/test/fnew-0112.test.js +311 -311
  173. package/test/fnew-03.test.js +422 -422
  174. package/test/graph-anchoring.test.js +184 -184
  175. package/test/graph-api.test.js +175 -175
  176. package/test/graph-inject-budget.test.js +103 -103
  177. package/test/graph-passive-confirm.test.js +91 -91
  178. package/test/graph-weight-evolution.test.js +104 -104
  179. package/test/heat.test.js +175 -175
  180. package/test/helpers/dream-mock.js +82 -82
  181. package/test/helpers/peer-worker.mjs +25 -25
  182. package/test/helpers/runtime-source.js +60 -60
  183. package/test/helpers/tar-builder.js +80 -80
  184. package/test/helpers/write-admission-samples.js +308 -308
  185. package/test/hot-memory.test.js +145 -145
  186. package/test/inject-content-cap.test.js +91 -91
  187. package/test/inject-first-round-bm25.test.js +89 -89
  188. package/test/inject-heat.test.js +77 -61
  189. package/test/inject-parent-gate.test.js +106 -106
  190. package/test/inject-pools.test.js +194 -194
  191. package/test/inject-recall.test.js +105 -105
  192. package/test/inject-rotation.test.js +161 -161
  193. package/test/inject.test.js +420 -420
  194. package/test/lang.test.js +87 -87
  195. package/test/lastrunat-persist.test.js +101 -101
  196. package/test/lib-smoke.test.js +96 -96
  197. package/test/llm-audit.test.js +598 -598
  198. package/test/llm-message-source.test.js +207 -207
  199. package/test/local-embedder.test.js +292 -292
  200. package/test/maintenance.test.js +391 -391
  201. package/test/mcp-stdio.test.js +385 -385
  202. package/test/mirror-dirty.test.js +424 -424
  203. package/test/mirror-edit-digest.test.js +187 -187
  204. package/test/mirror-generation.test.js +499 -499
  205. package/test/mirror-types.test.js +208 -208
  206. package/test/mirror.test.js +249 -249
  207. package/test/narrative-bars.test.js +162 -162
  208. package/test/organize.test.js +418 -418
  209. package/test/peer-blockers.test.js +193 -193
  210. package/test/placement.test.js +36 -0
  211. package/test/policy-epoch.test.js +259 -259
  212. package/test/pre-inject-gate.test.js +434 -0
  213. package/test/quality-filter.test.js +186 -186
  214. package/test/reasoning-effort.test.js +752 -752
  215. package/test/recall-anti-update.test.js +82 -82
  216. package/test/recall-evals.test.js +253 -253
  217. package/test/recall-layer.test.js +326 -326
  218. package/test/recall-stats.test.js +189 -189
  219. package/test/receipt-chain.test.js +451 -451
  220. package/test/reflection.test.js +226 -226
  221. package/test/reindex-backfill.test.js +62 -62
  222. package/test/reranker-single-logit.test.js +73 -73
  223. package/test/reranker.test.js +197 -197
  224. package/test/resident-status.test.js +83 -83
  225. package/test/runtime-adopt.test.js +206 -206
  226. package/test/runtime-cli.test.js +89 -89
  227. package/test/runtime-closure.test.js +193 -193
  228. package/test/runtime-download.test.js +302 -302
  229. package/test/runtime-layout.test.js +163 -163
  230. package/test/runtime-loader.test.js +255 -255
  231. package/test/runtime-manifest.test.js +159 -159
  232. package/test/runtime-model-fetch.test.js +348 -348
  233. package/test/runtime-provision.test.js +101 -101
  234. package/test/runtime-tarball.test.js +81 -81
  235. package/test/runtime-verify.test.js +319 -279
  236. package/test/scope-candidates.test.js +239 -239
  237. package/test/scope-explicit.test.js +452 -452
  238. package/test/scope-inject-soft.test.js +106 -106
  239. package/test/scope-retrieval.test.js +197 -197
  240. package/test/scope-storage.test.js +255 -255
  241. package/test/scope-strict.test.js +367 -343
  242. package/test/search-fusion.test.js +90 -90
  243. package/test/semantic.test.js +124 -124
  244. package/test/sensitive-scan.test.js +207 -207
  245. package/test/serve-bin.test.js +121 -0
  246. package/test/serve.test.js +196 -0
  247. package/test/service-search.test.js +174 -174
  248. package/test/service.test.js +405 -405
  249. package/test/settings.test.js +261 -261
  250. package/test/skip-invalid-restore.test.js +262 -262
  251. package/test/sleep-action-set.test.js +422 -422
  252. package/test/sleep-heat.test.js +126 -126
  253. package/test/sleep-scheduler-rearm.test.js +89 -89
  254. package/test/sleep.test.js +527 -527
  255. package/test/standalone-api.test.js +751 -544
  256. package/test/store-vector-cache.test.js +98 -98
  257. package/test/store.test.js +396 -396
  258. package/test/stress.test.js +209 -209
  259. package/test/summarize-occurred-at.test.js +127 -0
  260. package/test/summarize-reasoning-effort.test.js +189 -189
  261. package/test/summarize.test.js +1465 -1465
  262. package/test/supersede-state-tracking.test.js +394 -0
  263. package/test/test-count-sync.test.js +60 -60
  264. package/test/tools-dto-schema-matrix.test.js +325 -325
  265. package/test/tools-memory-get-schema.test.js +65 -65
  266. package/test/tools.test.js +428 -374
  267. package/test/updated-at-semantics.test.js +113 -113
  268. package/test/vector-index.test.js +221 -221
  269. package/test/version-check.test.js +152 -152
  270. package/test/webServer-optional.test.js +82 -82
  271. package/test/write-admission.test.js +668 -668
package/bin/cli.mjs CHANGED
@@ -1,689 +1,689 @@
1
- #!/usr/bin/env node
2
- /**
3
- * dsh-mneme CLI —— @modusensus/dsh-mneme 外部 API 命令行客户端
4
- *
5
- * 零依赖 ESM(Node >= 20,使用全局 fetch)。
6
- * 配置优先级:命令行 --url/--token > 环境变量 DSH_MNEME_URL / DSH_MNEME_TOKEN
7
- * > 配置文件 ~/.dsh-mneme/cli.json({"url","token"})
8
- * 默认服务地址:http://127.0.0.1:8790
9
- */
10
-
11
- import fs from 'node:fs';
12
- import fsp from 'node:fs/promises';
13
- import os from 'node:os';
14
- import path from 'node:path';
15
- import process from 'node:process';
16
- import { fileURLToPath } from 'node:url';
17
-
18
- const CLI_NAME = 'dsh-mneme';
19
- const DEFAULT_URL = 'http://127.0.0.1:8790';
20
- const CONFIG_DIR = path.join(os.homedir(), '.dsh-mneme');
21
- const CONFIG_PATH = path.join(CONFIG_DIR, 'cli.json');
22
- const MEMORY_TYPES = ['preference', 'project', 'decision', 'summary', 'history'];
23
- const SEARCH_MODES = ['keyword', 'vector', 'auto'];
24
- const REQUEST_TIMEOUT_MS = 10_000;
25
-
26
- function readPkgVersion() {
27
- try {
28
- const pkgPath = path.resolve(
29
- path.dirname(fileURLToPath(import.meta.url)),
30
- '..',
31
- 'package.json'
32
- );
33
- return JSON.parse(fs.readFileSync(pkgPath, 'utf8')).version ?? '?';
34
- } catch {
35
- return '?';
36
- }
37
- }
38
-
39
- const PKG_VERSION = readPkgVersion();
40
-
41
- const USAGE = `${CLI_NAME} —— DSH 记忆插件(@modusensus/dsh-mneme)外部 API 命令行客户端
42
-
43
- 用法:
44
- ${CLI_NAME} <命令> [参数] [选项]
45
-
46
- 配置(优先级从高到低):
47
- 1. 命令行参数 --url <url> / --token <token>
48
- 2. 环境变量 DSH_MNEME_URL / DSH_MNEME_TOKEN
49
- 3. 配置文件 ~/.dsh-mneme/cli.json(由 \`config set\` 写入)
50
- 未配置时使用默认地址:${DEFAULT_URL}
51
-
52
- 命令:
53
- config set <url> <token> 写入配置文件(token 省略时保留原值)
54
- config show 查看当前配置(token 打码显示)
55
- config path 打印配置文件路径
56
- status 服务状态(版本 / 记忆统计 / 实体 / 运行时长)
57
- list [--type t] [--min-importance n] [--source s]
58
- [--limit n] [--offset n] [--json]
59
- 列出记忆(type: preference | project | decision | summary | history)
60
- search <query> [--mode m] [--topk n] [--json]
61
- 搜索记忆(mode: keyword | vector | auto)
62
- get <id> [--json] 查看单条记忆
63
- add --type <t> --title <t> --content <c>
64
- [--importance n] [--tags a,b] [--source s] [--json]
65
- 新增记忆(type: preference | project | decision | summary | history)
66
- delete <id> 删除记忆
67
- reclaim [--older-than n] [--apply] [--vacuum] [--json]
68
- 存储无损回收(默认只报数字,不动数据)
69
- --older-than n 输入快照保留窗口(天,默认 7;0 = 全部)
70
- --apply 真的执行(不带就是 dry-run)
71
- --vacuum 执行后整库 VACUUM(需配 --apply)
72
- 只清「可由记忆库重建的输入快照」与「归档行的向量」,
73
- 一条记忆都不删;收益按 VACUUM 前后体积量
74
-
75
- 选项:
76
- --url <url> 覆盖服务地址
77
- --token <token> 覆盖访问 token
78
- --json 输出原始 JSON
79
- -h, --help 显示本帮助
80
- -V, --version 显示版本号
81
-
82
- 说明:
83
- token 在 DSH 面板「设置 → 外部访问」或插件设置中查看;
84
- 除 GET /health 外,所有外部 API 路由均需 Bearer token。
85
-
86
- 示例:
87
- ${CLI_NAME} config set ${DEFAULT_URL} my-token
88
- ${CLI_NAME} status
89
- ${CLI_NAME} list --type project --limit 10
90
- ${CLI_NAME} search "部署流程" --mode vector --topk 5
91
- ${CLI_NAME} add --type decision --title "采用 SQLite" --content "存储层使用 node:sqlite" --importance 4 --tags 存储,决策
92
- ${CLI_NAME} get 42
93
- ${CLI_NAME} delete 42
94
- ${CLI_NAME} reclaim (先看:会清几行、库多大)
95
- ${CLI_NAME} reclaim --apply --vacuum (确认后执行,并把空间真的收回来)`;
96
-
97
- /* ---------------------------------- 参数解析 ---------------------------------- */
98
-
99
- function parseArgv(argv) {
100
- const positionals = [];
101
- const flags = {};
102
- for (let i = 0; i < argv.length; i++) {
103
- const arg = argv[i];
104
- if (arg === '--') {
105
- positionals.push(...argv.slice(i + 1));
106
- break;
107
- }
108
- if (arg.startsWith('--')) {
109
- let key = arg.slice(2);
110
- let value;
111
- const eq = key.indexOf('=');
112
- if (eq >= 0) {
113
- value = key.slice(eq + 1);
114
- key = key.slice(0, eq);
115
- } else if (i + 1 < argv.length && !argv[i + 1].startsWith('--') && argv[i + 1] !== '--') {
116
- value = argv[++i];
117
- } else {
118
- value = true;
119
- }
120
- flags[key.toLowerCase()] = value;
121
- } else {
122
- positionals.push(arg);
123
- }
124
- }
125
- return { positionals, flags };
126
- }
127
-
128
- function flagValue(flags, ...names) {
129
- for (const name of names) {
130
- const value = flags[name.toLowerCase()];
131
- if (value !== undefined && value !== true && value !== '') return value;
132
- }
133
- return undefined;
134
- }
135
-
136
- function flagBool(flags, ...names) {
137
- for (const name of names) {
138
- const value = flags[name.toLowerCase()];
139
- if (value !== undefined) return value === true || value === 'true' || value === '';
140
- }
141
- return false;
142
- }
143
-
144
- /* ---------------------------------- 配置解析 ---------------------------------- */
145
-
146
- function readConfigFile() {
147
- try {
148
- const data = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8'));
149
- return data && typeof data === 'object' && !Array.isArray(data) ? data : {};
150
- } catch {
151
- return {};
152
- }
153
- }
154
-
155
- function firstNonEmpty(...values) {
156
- for (const value of values) {
157
- if (typeof value === 'string' && value.trim() !== '') return value.trim();
158
- }
159
- return undefined;
160
- }
161
-
162
- function resolveConfig(flags) {
163
- const file = readConfigFile();
164
- const url =
165
- firstNonEmpty(flagValue(flags, 'url'), process.env.DSH_MNEME_URL, file.url) ?? DEFAULT_URL;
166
- const token =
167
- firstNonEmpty(flagValue(flags, 'token'), process.env.DSH_MNEME_TOKEN, file.token) ?? '';
168
- return { url: url.replace(/\/+$/, ''), token, jsonMode: false };
169
- }
170
-
171
- function maskToken(token) {
172
- if (!token) return '(未设置)';
173
- if (token.length <= 8) return '****';
174
- return `${token.slice(0, 4)}****${token.slice(-4)}`;
175
- }
176
-
177
- /* ---------------------------------- 输出与错误 ---------------------------------- */
178
-
179
- function stringify(value) {
180
- return JSON.stringify(value, null, 2);
181
- }
182
-
183
- function fail(cfg, message, { rawJson } = {}) {
184
- if (cfg.jsonMode) {
185
- console.error(rawJson !== undefined ? rawJson : stringify({ error: message }));
186
- } else {
187
- console.error(message);
188
- }
189
- process.exit(1);
190
- }
191
-
192
- function failHttp(cfg, status, pathname, data, text) {
193
- const serverError =
194
- data && typeof data === 'object' && data.error
195
- ? String(data.error)
196
- : (text || '').slice(0, 200);
197
- let hint = '';
198
- if (status === 401) {
199
- hint =
200
- `\n访问 token 缺失或无效。token 可在 DSH 面板「设置 → 外部访问」或插件设置中查看,\n` +
201
- `然后用 \`${CLI_NAME} config set <url> <token>\`、环境变量 DSH_MNEME_TOKEN 或 --token 配置。`;
202
- } else if (status === 404) {
203
- hint = `\n资源不存在:${pathname}`;
204
- }
205
- fail(cfg, `请求失败(HTTP ${status})${serverError ? `:${serverError}` : ''} [${pathname}]${hint}`, {
206
- rawJson: cfg.jsonMode && text ? text : undefined,
207
- });
208
- }
209
-
210
- function failNetwork(cfg, url, err) {
211
- const timedOut = err && (err.name === 'TimeoutError' || err.name === 'AbortError');
212
- const reason = timedOut
213
- ? `请求超时(${REQUEST_TIMEOUT_MS / 1000} 秒)`
214
- : `无法连接到服务(${err?.code ?? err?.cause?.code ?? err?.message ?? '未知错误'})`;
215
- fail(
216
- cfg,
217
- `${reason}:${url}\n` +
218
- `请确认 DSH 已启动、插件外部 API 已开启,且地址正确(默认 ${DEFAULT_URL})。`
219
- );
220
- }
221
-
222
- function requireToken(cfg) {
223
- if (cfg.token) return;
224
- fail(
225
- cfg,
226
- [
227
- '未配置访问 token,无法调用该命令(外部 API 需要 Bearer 鉴权)。',
228
- '',
229
- 'token 可在 DSH 面板「设置 → 外部访问」或插件设置中查看,然后任选其一配置:',
230
- ` 1. ${CLI_NAME} config set <url> <token>`,
231
- ' 2. 环境变量 DSH_MNEME_TOKEN=<token>',
232
- ' 3. 命令行参数 --token <token>',
233
- ].join('\n')
234
- );
235
- }
236
-
237
- function parseIntArg(cfg, value, label) {
238
- if (value === undefined || value === true || value === '') return undefined;
239
- const n = Number(value);
240
- if (!Number.isInteger(n) || n < 0) {
241
- fail(cfg, `无效的 ${label}: ${value}(应为非负整数)`);
242
- }
243
- return n;
244
- }
245
-
246
- /* ---------------------------------- HTTP 请求 ---------------------------------- */
247
-
248
- async function apiRequest(cfg, method, pathname, { query, body } = {}) {
249
- let url = cfg.url + pathname;
250
- if (query) {
251
- const params = new URLSearchParams();
252
- for (const [key, value] of Object.entries(query)) {
253
- if (value !== undefined && value !== null && value !== '') {
254
- params.set(key, String(value));
255
- }
256
- }
257
- const qs = params.toString();
258
- if (qs) url += `?${qs}`;
259
- }
260
-
261
- const headers = { Accept: 'application/json' };
262
- if (cfg.token) headers.Authorization = `Bearer ${cfg.token}`;
263
- if (body !== undefined) headers['Content-Type'] = 'application/json';
264
-
265
- let res;
266
- try {
267
- res = await fetch(url, {
268
- method,
269
- headers,
270
- body: body !== undefined ? JSON.stringify(body) : undefined,
271
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
272
- });
273
- } catch (err) {
274
- failNetwork(cfg, url, err);
275
- }
276
-
277
- const text = await res.text();
278
- let data = null;
279
- try {
280
- data = text ? JSON.parse(text) : null;
281
- } catch {
282
- // 非 JSON 响应体,保留原始文本用于报错展示
283
- }
284
-
285
- if (!res.ok) {
286
- failHttp(cfg, res.status, pathname, data, text);
287
- }
288
- return data;
289
- }
290
-
291
- /* ---------------------------------- 结果格式化 ---------------------------------- */
292
-
293
- function formatTimestamp(value) {
294
- if (!value) return '';
295
- const s = String(value);
296
- return s.length >= 10 ? s.slice(0, 10) : s;
297
- }
298
-
299
- function formatMemoryLine(item) {
300
- const id = item?.id ?? '?';
301
- const type = item?.type ?? '?';
302
- const importance = item?.importance != null ? ` ★${item.importance}` : '';
303
- const title = item?.title ? ` ${item.title}` : '';
304
- const tags =
305
- Array.isArray(item?.tags) && item.tags.length ? ` [${item.tags.join(',')}]` : '';
306
- const date = formatTimestamp(item?.created_at ?? item?.createdAt);
307
- return ` #${id} [${type}]${importance}${title}${tags}${date ? ` (${date})` : ''}`;
308
- }
309
-
310
- function printMemoryItems(payload, { withMode = false } = {}) {
311
- const items = Array.isArray(payload?.items) ? payload.items : [];
312
- const total = payload?.total ?? items.length;
313
- if (withMode && payload?.mode) console.log(`搜索模式: ${payload.mode}`);
314
- console.log(`共 ${total} 条,本次显示 ${items.length} 条`);
315
- if (!items.length) return;
316
- console.log('');
317
- for (const item of items) {
318
- const score = item?.score ?? item?.similarity;
319
- const scoreText =
320
- typeof score === 'number' && Number.isFinite(score) ? ` (score ${score.toFixed(3)})` : '';
321
- console.log(formatMemoryLine(item) + scoreText);
322
- const content =
323
- typeof item?.content === 'string' ? item.content.replace(/\s+/g, ' ').trim() : '';
324
- if (content) {
325
- console.log(` ${content.length > 80 ? `${content.slice(0, 80)}…` : content}`);
326
- }
327
- }
328
- }
329
-
330
- function printMemoryDetail(item) {
331
- if (!item || typeof item !== 'object') {
332
- console.log(stringify(item ?? null));
333
- return;
334
- }
335
- const fields = [];
336
- if (item.id !== undefined) fields.push(`id: ${item.id}`);
337
- if (item.type !== undefined) fields.push(`类型: ${item.type}`);
338
- if (item.importance !== undefined) fields.push(`重要性: ${item.importance}`);
339
- if (item.title !== undefined) fields.push(`标题: ${item.title}`);
340
- if (item.tags !== undefined) {
341
- fields.push(`标签: ${Array.isArray(item.tags) ? item.tags.join(', ') : item.tags}`);
342
- }
343
- if (item.source !== undefined) fields.push(`来源: ${item.source}`);
344
- const created = item.created_at ?? item.createdAt;
345
- if (created) fields.push(`创建时间: ${created}`);
346
- for (const line of fields) console.log(line);
347
- if (item.content !== undefined) console.log(`\n${item.content}`);
348
- }
349
-
350
- function printStatus(data) {
351
- console.log(`服务版本: ${data?.version ?? '?'}`);
352
- console.log(`运行时长: ${data?.uptime_s ?? data?.uptimeS ?? '?'} 秒`);
353
- const memories = data?.memories ?? {};
354
- console.log(`记忆总数: ${memories.total ?? '?'}`);
355
- const byType = memories.byType;
356
- if (Array.isArray(byType)) {
357
- for (const row of byType) {
358
- console.log(` - ${row?.type ?? row?.name ?? '?'}: ${row?.count ?? row?.total ?? '?'}`);
359
- }
360
- } else if (byType && typeof byType === 'object') {
361
- for (const [type, count] of Object.entries(byType)) {
362
- console.log(` - ${type}: ${count}`);
363
- }
364
- }
365
- const entities = data?.entities;
366
- if (entities != null) {
367
- const total =
368
- typeof entities === 'object' && !Array.isArray(entities)
369
- ? entities.total
370
- : entities;
371
- console.log(`实体数量: ${total ?? '?'}`);
372
- }
373
- }
374
-
375
- /* ---------------------------------- 子命令 ---------------------------------- */
376
-
377
- async function cmdConfig(cfg, sub, rest) {
378
- const subCmd = sub || 'show';
379
-
380
- if (subCmd === 'set') {
381
- const [url, tokenArg] = rest;
382
- if (!url) {
383
- fail(
384
- cfg,
385
- `用法: ${CLI_NAME} config set <url> <token>\n示例: ${CLI_NAME} config set ${DEFAULT_URL} my-token`
386
- );
387
- }
388
- if (!/^https?:\/\//i.test(url)) {
389
- fail(cfg, `无效的服务地址: ${url}(应以 http:// 或 https:// 开头)`);
390
- }
391
- const existing = readConfigFile();
392
- const token = tokenArg ?? existing.token ?? '';
393
- await fsp.mkdir(CONFIG_DIR, { recursive: true });
394
- await fsp.writeFile(CONFIG_PATH, `${JSON.stringify({ url, token }, null, 2)}\n`, 'utf8');
395
- if (cfg.jsonMode) {
396
- console.log(stringify({ configPath: CONFIG_PATH, url, tokenConfigured: Boolean(token) }));
397
- } else {
398
- console.log(`已写入配置文件: ${CONFIG_PATH}`);
399
- console.log(` url: ${url}`);
400
- console.log(` token: ${maskToken(token)}`);
401
- }
402
- return;
403
- }
404
-
405
- if (subCmd === 'show') {
406
- const hasFile = fs.existsSync(CONFIG_PATH);
407
- const file = readConfigFile();
408
- if (cfg.jsonMode) {
409
- console.log(
410
- stringify({
411
- configPath: CONFIG_PATH,
412
- configExists: hasFile,
413
- url: file.url ?? DEFAULT_URL,
414
- token: maskToken(file.token),
415
- })
416
- );
417
- return;
418
- }
419
- if (!hasFile) {
420
- console.log(`尚未创建配置文件(未配置): ${CONFIG_PATH}`);
421
- console.log('');
422
- console.log(`可运行 \`${CLI_NAME} config set <url> <token>\` 创建配置;`);
423
- console.log('token 可在 DSH 面板「设置 → 外部访问」或插件设置中查看。');
424
- console.log(
425
- `未配置时使用默认地址 ${DEFAULT_URL},也可用环境变量 DSH_MNEME_URL / DSH_MNEME_TOKEN。`
426
- );
427
- return;
428
- }
429
- console.log(`配置文件: ${CONFIG_PATH}`);
430
- console.log(` url: ${file.url ?? `(未设置,默认 ${DEFAULT_URL})`}`);
431
- console.log(` token: ${maskToken(file.token)}`);
432
- console.log('');
433
- console.log('配置优先级: --url/--token > 环境变量 DSH_MNEME_URL / DSH_MNEME_TOKEN > 配置文件');
434
- return;
435
- }
436
-
437
- if (subCmd === 'path') {
438
- console.log(CONFIG_PATH);
439
- return;
440
- }
441
-
442
- fail(cfg, `未知的 config 子命令: ${subCmd}\n可用子命令: set / show / path`);
443
- }
444
-
445
- async function cmdStatus(cfg) {
446
- requireToken(cfg);
447
- const data = await apiRequest(cfg, 'GET', '/status');
448
- if (cfg.jsonMode) {
449
- console.log(stringify(data));
450
- } else {
451
- printStatus(data);
452
- }
453
- }
454
-
455
- async function cmdList(cfg, flags) {
456
- requireToken(cfg);
457
- const query = {
458
- type: flagValue(flags, 'type'),
459
- minImportance: parseIntArg(cfg, flagValue(flags, 'min-importance', 'minImportance'), '--min-importance'),
460
- source: flagValue(flags, 'source'),
461
- limit: parseIntArg(cfg, flagValue(flags, 'limit'), '--limit'),
462
- offset: parseIntArg(cfg, flagValue(flags, 'offset'), '--offset'),
463
- };
464
- const data = await apiRequest(cfg, 'GET', '/memories', { query });
465
- if (cfg.jsonMode) {
466
- console.log(stringify(data));
467
- } else {
468
- printMemoryItems(data);
469
- }
470
- }
471
-
472
- async function cmdSearch(cfg, rest, flags) {
473
- requireToken(cfg);
474
- const q = rest[0];
475
- if (!q) {
476
- fail(
477
- cfg,
478
- `用法: ${CLI_NAME} search <query> [--mode m] [--topk n]\n` +
479
- `示例: ${CLI_NAME} search "部署流程" --mode vector --topk 5`
480
- );
481
- }
482
- const mode = flagValue(flags, 'mode');
483
- if (mode !== undefined && !SEARCH_MODES.includes(mode)) {
484
- fail(cfg, `无效的 --mode: ${mode}(可选: ${SEARCH_MODES.join(' | ')})`);
485
- }
486
- const topK = parseIntArg(cfg, flagValue(flags, 'topk', 'top-k', 'topK'), '--topk');
487
- const data = await apiRequest(cfg, 'GET', '/search', { query: { q, mode, topK } });
488
- if (cfg.jsonMode) {
489
- console.log(stringify(data));
490
- } else {
491
- printMemoryItems(data, { withMode: true });
492
- }
493
- }
494
-
495
- async function cmdGet(cfg, rest) {
496
- requireToken(cfg);
497
- const id = rest[0];
498
- if (!id) {
499
- fail(cfg, `用法: ${CLI_NAME} get <id> [--json]`);
500
- }
501
- const data = await apiRequest(cfg, 'GET', `/memories/${encodeURIComponent(id)}`);
502
- if (cfg.jsonMode) {
503
- console.log(stringify(data));
504
- } else {
505
- printMemoryDetail(data);
506
- }
507
- }
508
-
509
- async function cmdAdd(cfg, flags) {
510
- requireToken(cfg);
511
- const type = flagValue(flags, 'type');
512
- const title = flagValue(flags, 'title');
513
- const content = flagValue(flags, 'content');
514
- if (!type || !title || !content) {
515
- fail(
516
- cfg,
517
- `用法: ${CLI_NAME} add --type <${MEMORY_TYPES.join('|')}> --title <标题> --content <内容>\n` +
518
- ` [--importance n] [--tags a,b] [--source s]\n\n` +
519
- `示例: ${CLI_NAME} add --type decision --title "采用 SQLite" --content "存储层使用 node:sqlite"`
520
- );
521
- }
522
- if (!MEMORY_TYPES.includes(type)) {
523
- fail(cfg, `无效的 --type: ${type}(可选: ${MEMORY_TYPES.join(' | ')})`);
524
- }
525
- const importanceRaw = flagValue(flags, 'importance');
526
- let importance;
527
- if (importanceRaw !== undefined) {
528
- importance = Number(importanceRaw);
529
- if (!Number.isInteger(importance) || importance < 1 || importance > 5) {
530
- fail(cfg, `无效的 --importance: ${importanceRaw}(应为 1-5 的整数)`);
531
- }
532
- }
533
- const tagsRaw = flagValue(flags, 'tags');
534
- const tags =
535
- tagsRaw !== undefined
536
- ? tagsRaw.split(',').map((t) => t.trim()).filter(Boolean)
537
- : undefined;
538
- const source = flagValue(flags, 'source');
539
-
540
- const body = { type, title, content };
541
- if (importance !== undefined) body.importance = importance;
542
- if (tags) body.tags = tags;
543
- if (source) body.source = source;
544
-
545
- const data = await apiRequest(cfg, 'POST', '/memories', { body });
546
- if (cfg.jsonMode) {
547
- console.log(stringify(data));
548
- } else {
549
- console.log('已添加记忆:');
550
- printMemoryDetail(data);
551
- }
552
- }
553
-
554
- async function cmdDelete(cfg, rest) {
555
- requireToken(cfg);
556
- const id = rest[0];
557
- if (!id) {
558
- fail(cfg, `用法: ${CLI_NAME} delete <id>`);
559
- }
560
- const data = await apiRequest(cfg, 'DELETE', `/memories/${encodeURIComponent(id)}`);
561
- if (cfg.jsonMode) {
562
- console.log(stringify(data));
563
- } else {
564
- console.log(`已删除记忆 ${id}`);
565
- }
566
- }
567
-
568
- function formatBytes(bytes) {
569
- if (typeof bytes !== 'number' || !Number.isFinite(bytes)) return '?';
570
- const mb = bytes / (1024 * 1024);
571
- if (mb >= 1) return `${mb.toFixed(1)} MB`;
572
- return `${(bytes / 1024).toFixed(1)} KB`;
573
- }
574
-
575
- function printReclaim(report, { applied }) {
576
- const planned = report?.planned ?? {};
577
- const cleared = report?.cleared ?? {};
578
- const columnBytes = report?.column_bytes ?? {};
579
- const size = report?.size ?? {};
580
- console.log(`存储无损回收(${applied ? '已执行' : 'dry-run,未改动任何数据'})`);
581
- console.log(` 输入快照保留窗口: ${report?.olderThanDays ?? '?'} 天(cutoff ${report?.cutoff ?? '?'})`);
582
- const rows = (o) => `dream_runs.input ${o.dream_run_inputs ?? 0} 行 / 归档行向量 ${o.archived_embeddings ?? 0} 行`;
583
- console.log(` ${applied ? '已清理' : '将清理'}: ${rows(applied ? cleared : planned)}`);
584
- console.log(
585
- ` 列文本大小(上界,非回收量): ${formatBytes(columnBytes.dream_run_inputs)} / ${formatBytes(columnBytes.archived_embeddings)}`
586
- );
587
- if (!applied) {
588
- console.log(
589
- ` 库文件: ${formatBytes(size.before_bytes)}(空闲页 ${size.freelist_pages ?? '?'} 页,可立刻回收约 ${formatBytes(size.freelist_bytes)})`
590
- );
591
- console.log('');
592
- console.log(' 上面是 dry-run 的数字。确认后执行:');
593
- console.log(` ${CLI_NAME} reclaim --apply --vacuum`);
594
- return;
595
- }
596
- const freed =
597
- typeof size.before_bytes === 'number' && typeof size.after_bytes === 'number'
598
- ? size.before_bytes - size.after_bytes
599
- : null;
600
- if (report?.vacuum?.error) {
601
- console.log(` VACUUM: 失败(${String(report.vacuum.error).slice(0, 120)})`);
602
- console.log(' 清理已经完成且不可逆,文件暂时不会变小;库多半被别的进程占着锁,');
603
- console.log(' 稍后重跑一次 `reclaim --apply --vacuum` 即可(清理是幂等的)。');
604
- } else {
605
- console.log(
606
- ` VACUUM: ${report?.vacuum?.ran ? `已跑(${report.vacuum.duration_ms ?? '?'} ms)` : '未跑(未带 --vacuum,文件不会变小)'}`
607
- );
608
- }
609
- console.log(
610
- ` 库文件: ${formatBytes(size.before_bytes)} → ${formatBytes(size.after_bytes)}` +
611
- (freed !== null && freed > 0 ? `(释放 ${formatBytes(freed)})` : '')
612
- );
613
- console.log(` 耗时: ${report?.duration_ms ?? '?'} ms`);
614
- if (report?.receipt) console.log(` 回执: llm_audit_logs #${report.receipt}`);
615
- }
616
-
617
- async function cmdReclaim(cfg, flags) {
618
- requireToken(cfg);
619
- const applied = flagBool(flags, 'apply');
620
- const vacuum = flagBool(flags, 'vacuum');
621
- if (vacuum && !applied) {
622
- fail(
623
- cfg,
624
- `--vacuum 需要配 --apply:dry-run 不改数据,也就没有可回收的页。\n` +
625
- `先看数字,再执行:${CLI_NAME} reclaim --apply --vacuum`
626
- );
627
- }
628
- const olderThanDays = parseIntArg(cfg, flagValue(flags, 'older-than', 'olderThanDays'), '--older-than');
629
- const body = { dryRun: !applied };
630
- if (applied) {
631
- // 服务端要求显式确认:这两步不可逆,缺 confirm 只会拿回一份 dry-run 报告。
632
- body.confirm = true;
633
- }
634
- if (olderThanDays !== undefined) body.olderThanDays = olderThanDays;
635
- if (vacuum) body.vacuum = true;
636
- const data = await apiRequest(cfg, 'POST', '/maintenance/reclaim', { body });
637
- if (cfg.jsonMode) {
638
- console.log(stringify(data));
639
- } else {
640
- printReclaim(data, { applied });
641
- }
642
- }
643
-
644
- /* ---------------------------------- 入口 ---------------------------------- */
645
- async function main(argv) {
646
- const { positionals, flags } = parseArgv(argv);
647
- const cmd = positionals[0];
648
- const rest = positionals.slice(1);
649
-
650
- if (!cmd || cmd === '-h' || cmd === '--help' || cmd === 'help') {
651
- console.log(USAGE);
652
- return;
653
- }
654
- if (cmd === '-V' || cmd === '--version' || cmd === 'version') {
655
- console.log(PKG_VERSION);
656
- return;
657
- }
658
-
659
- const cfg = resolveConfig(flags);
660
- cfg.jsonMode = flagBool(flags, 'json');
661
-
662
- switch (cmd) {
663
- case 'config':
664
- return cmdConfig(cfg, rest[0], rest.slice(1));
665
- case 'status':
666
- return cmdStatus(cfg);
667
- case 'list':
668
- case 'ls':
669
- return cmdList(cfg, flags);
670
- case 'search':
671
- return cmdSearch(cfg, rest, flags);
672
- case 'get':
673
- return cmdGet(cfg, rest);
674
- case 'add':
675
- return cmdAdd(cfg, flags);
676
- case 'delete':
677
- case 'rm':
678
- return cmdDelete(cfg, rest);
679
- case 'reclaim':
680
- return cmdReclaim(cfg, flags);
681
- default:
682
- fail(cfg, `未知命令: ${cmd}\n运行 \`${CLI_NAME} --help\` 查看帮助。`);
683
- }
684
- }
685
-
686
- main(process.argv.slice(2)).catch((err) => {
687
- console.error(err?.stack ?? String(err));
688
- process.exit(1);
689
- });
1
+ #!/usr/bin/env node
2
+ /**
3
+ * dsh-mneme CLI —— @modusensus/dsh-mneme 外部 API 命令行客户端
4
+ *
5
+ * 零依赖 ESM(Node >= 20,使用全局 fetch)。
6
+ * 配置优先级:命令行 --url/--token > 环境变量 DSH_MNEME_URL / DSH_MNEME_TOKEN
7
+ * > 配置文件 ~/.dsh-mneme/cli.json({"url","token"})
8
+ * 默认服务地址:http://127.0.0.1:8790
9
+ */
10
+
11
+ import fs from 'node:fs';
12
+ import fsp from 'node:fs/promises';
13
+ import os from 'node:os';
14
+ import path from 'node:path';
15
+ import process from 'node:process';
16
+ import { fileURLToPath } from 'node:url';
17
+
18
+ const CLI_NAME = 'dsh-mneme';
19
+ const DEFAULT_URL = 'http://127.0.0.1:8790';
20
+ const CONFIG_DIR = path.join(os.homedir(), '.dsh-mneme');
21
+ const CONFIG_PATH = path.join(CONFIG_DIR, 'cli.json');
22
+ const MEMORY_TYPES = ['preference', 'project', 'decision', 'summary', 'history'];
23
+ const SEARCH_MODES = ['keyword', 'vector', 'auto'];
24
+ const REQUEST_TIMEOUT_MS = 10_000;
25
+
26
+ function readPkgVersion() {
27
+ try {
28
+ const pkgPath = path.resolve(
29
+ path.dirname(fileURLToPath(import.meta.url)),
30
+ '..',
31
+ 'package.json'
32
+ );
33
+ return JSON.parse(fs.readFileSync(pkgPath, 'utf8')).version ?? '?';
34
+ } catch {
35
+ return '?';
36
+ }
37
+ }
38
+
39
+ const PKG_VERSION = readPkgVersion();
40
+
41
+ const USAGE = `${CLI_NAME} —— DSH 记忆插件(@modusensus/dsh-mneme)外部 API 命令行客户端
42
+
43
+ 用法:
44
+ ${CLI_NAME} <命令> [参数] [选项]
45
+
46
+ 配置(优先级从高到低):
47
+ 1. 命令行参数 --url <url> / --token <token>
48
+ 2. 环境变量 DSH_MNEME_URL / DSH_MNEME_TOKEN
49
+ 3. 配置文件 ~/.dsh-mneme/cli.json(由 \`config set\` 写入)
50
+ 未配置时使用默认地址:${DEFAULT_URL}
51
+
52
+ 命令:
53
+ config set <url> <token> 写入配置文件(token 省略时保留原值)
54
+ config show 查看当前配置(token 打码显示)
55
+ config path 打印配置文件路径
56
+ status 服务状态(版本 / 记忆统计 / 实体 / 运行时长)
57
+ list [--type t] [--min-importance n] [--source s]
58
+ [--limit n] [--offset n] [--json]
59
+ 列出记忆(type: preference | project | decision | summary | history)
60
+ search <query> [--mode m] [--topk n] [--json]
61
+ 搜索记忆(mode: keyword | vector | auto)
62
+ get <id> [--json] 查看单条记忆
63
+ add --type <t> --title <t> --content <c>
64
+ [--importance n] [--tags a,b] [--source s] [--json]
65
+ 新增记忆(type: preference | project | decision | summary | history)
66
+ delete <id> 删除记忆
67
+ reclaim [--older-than n] [--apply] [--vacuum] [--json]
68
+ 存储无损回收(默认只报数字,不动数据)
69
+ --older-than n 输入快照保留窗口(天,默认 7;0 = 全部)
70
+ --apply 真的执行(不带就是 dry-run)
71
+ --vacuum 执行后整库 VACUUM(需配 --apply)
72
+ 只清「可由记忆库重建的输入快照」与「归档行的向量」,
73
+ 一条记忆都不删;收益按 VACUUM 前后体积量
74
+
75
+ 选项:
76
+ --url <url> 覆盖服务地址
77
+ --token <token> 覆盖访问 token
78
+ --json 输出原始 JSON
79
+ -h, --help 显示本帮助
80
+ -V, --version 显示版本号
81
+
82
+ 说明:
83
+ token 在 DSH 面板「设置 → 外部访问」或插件设置中查看;
84
+ 除 GET /health 外,所有外部 API 路由均需 Bearer token。
85
+
86
+ 示例:
87
+ ${CLI_NAME} config set ${DEFAULT_URL} my-token
88
+ ${CLI_NAME} status
89
+ ${CLI_NAME} list --type project --limit 10
90
+ ${CLI_NAME} search "部署流程" --mode vector --topk 5
91
+ ${CLI_NAME} add --type decision --title "采用 SQLite" --content "存储层使用 node:sqlite" --importance 4 --tags 存储,决策
92
+ ${CLI_NAME} get 42
93
+ ${CLI_NAME} delete 42
94
+ ${CLI_NAME} reclaim (先看:会清几行、库多大)
95
+ ${CLI_NAME} reclaim --apply --vacuum (确认后执行,并把空间真的收回来)`;
96
+
97
+ /* ---------------------------------- 参数解析 ---------------------------------- */
98
+
99
+ function parseArgv(argv) {
100
+ const positionals = [];
101
+ const flags = {};
102
+ for (let i = 0; i < argv.length; i++) {
103
+ const arg = argv[i];
104
+ if (arg === '--') {
105
+ positionals.push(...argv.slice(i + 1));
106
+ break;
107
+ }
108
+ if (arg.startsWith('--')) {
109
+ let key = arg.slice(2);
110
+ let value;
111
+ const eq = key.indexOf('=');
112
+ if (eq >= 0) {
113
+ value = key.slice(eq + 1);
114
+ key = key.slice(0, eq);
115
+ } else if (i + 1 < argv.length && !argv[i + 1].startsWith('--') && argv[i + 1] !== '--') {
116
+ value = argv[++i];
117
+ } else {
118
+ value = true;
119
+ }
120
+ flags[key.toLowerCase()] = value;
121
+ } else {
122
+ positionals.push(arg);
123
+ }
124
+ }
125
+ return { positionals, flags };
126
+ }
127
+
128
+ function flagValue(flags, ...names) {
129
+ for (const name of names) {
130
+ const value = flags[name.toLowerCase()];
131
+ if (value !== undefined && value !== true && value !== '') return value;
132
+ }
133
+ return undefined;
134
+ }
135
+
136
+ function flagBool(flags, ...names) {
137
+ for (const name of names) {
138
+ const value = flags[name.toLowerCase()];
139
+ if (value !== undefined) return value === true || value === 'true' || value === '';
140
+ }
141
+ return false;
142
+ }
143
+
144
+ /* ---------------------------------- 配置解析 ---------------------------------- */
145
+
146
+ function readConfigFile() {
147
+ try {
148
+ const data = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8'));
149
+ return data && typeof data === 'object' && !Array.isArray(data) ? data : {};
150
+ } catch {
151
+ return {};
152
+ }
153
+ }
154
+
155
+ function firstNonEmpty(...values) {
156
+ for (const value of values) {
157
+ if (typeof value === 'string' && value.trim() !== '') return value.trim();
158
+ }
159
+ return undefined;
160
+ }
161
+
162
+ function resolveConfig(flags) {
163
+ const file = readConfigFile();
164
+ const url =
165
+ firstNonEmpty(flagValue(flags, 'url'), process.env.DSH_MNEME_URL, file.url) ?? DEFAULT_URL;
166
+ const token =
167
+ firstNonEmpty(flagValue(flags, 'token'), process.env.DSH_MNEME_TOKEN, file.token) ?? '';
168
+ return { url: url.replace(/\/+$/, ''), token, jsonMode: false };
169
+ }
170
+
171
+ function maskToken(token) {
172
+ if (!token) return '(未设置)';
173
+ if (token.length <= 8) return '****';
174
+ return `${token.slice(0, 4)}****${token.slice(-4)}`;
175
+ }
176
+
177
+ /* ---------------------------------- 输出与错误 ---------------------------------- */
178
+
179
+ function stringify(value) {
180
+ return JSON.stringify(value, null, 2);
181
+ }
182
+
183
+ function fail(cfg, message, { rawJson } = {}) {
184
+ if (cfg.jsonMode) {
185
+ console.error(rawJson !== undefined ? rawJson : stringify({ error: message }));
186
+ } else {
187
+ console.error(message);
188
+ }
189
+ process.exit(1);
190
+ }
191
+
192
+ function failHttp(cfg, status, pathname, data, text) {
193
+ const serverError =
194
+ data && typeof data === 'object' && data.error
195
+ ? String(data.error)
196
+ : (text || '').slice(0, 200);
197
+ let hint = '';
198
+ if (status === 401) {
199
+ hint =
200
+ `\n访问 token 缺失或无效。token 可在 DSH 面板「设置 → 外部访问」或插件设置中查看,\n` +
201
+ `然后用 \`${CLI_NAME} config set <url> <token>\`、环境变量 DSH_MNEME_TOKEN 或 --token 配置。`;
202
+ } else if (status === 404) {
203
+ hint = `\n资源不存在:${pathname}`;
204
+ }
205
+ fail(cfg, `请求失败(HTTP ${status})${serverError ? `:${serverError}` : ''} [${pathname}]${hint}`, {
206
+ rawJson: cfg.jsonMode && text ? text : undefined,
207
+ });
208
+ }
209
+
210
+ function failNetwork(cfg, url, err) {
211
+ const timedOut = err && (err.name === 'TimeoutError' || err.name === 'AbortError');
212
+ const reason = timedOut
213
+ ? `请求超时(${REQUEST_TIMEOUT_MS / 1000} 秒)`
214
+ : `无法连接到服务(${err?.code ?? err?.cause?.code ?? err?.message ?? '未知错误'})`;
215
+ fail(
216
+ cfg,
217
+ `${reason}:${url}\n` +
218
+ `请确认 DSH 已启动、插件外部 API 已开启,且地址正确(默认 ${DEFAULT_URL})。`
219
+ );
220
+ }
221
+
222
+ function requireToken(cfg) {
223
+ if (cfg.token) return;
224
+ fail(
225
+ cfg,
226
+ [
227
+ '未配置访问 token,无法调用该命令(外部 API 需要 Bearer 鉴权)。',
228
+ '',
229
+ 'token 可在 DSH 面板「设置 → 外部访问」或插件设置中查看,然后任选其一配置:',
230
+ ` 1. ${CLI_NAME} config set <url> <token>`,
231
+ ' 2. 环境变量 DSH_MNEME_TOKEN=<token>',
232
+ ' 3. 命令行参数 --token <token>',
233
+ ].join('\n')
234
+ );
235
+ }
236
+
237
+ function parseIntArg(cfg, value, label) {
238
+ if (value === undefined || value === true || value === '') return undefined;
239
+ const n = Number(value);
240
+ if (!Number.isInteger(n) || n < 0) {
241
+ fail(cfg, `无效的 ${label}: ${value}(应为非负整数)`);
242
+ }
243
+ return n;
244
+ }
245
+
246
+ /* ---------------------------------- HTTP 请求 ---------------------------------- */
247
+
248
+ async function apiRequest(cfg, method, pathname, { query, body } = {}) {
249
+ let url = cfg.url + pathname;
250
+ if (query) {
251
+ const params = new URLSearchParams();
252
+ for (const [key, value] of Object.entries(query)) {
253
+ if (value !== undefined && value !== null && value !== '') {
254
+ params.set(key, String(value));
255
+ }
256
+ }
257
+ const qs = params.toString();
258
+ if (qs) url += `?${qs}`;
259
+ }
260
+
261
+ const headers = { Accept: 'application/json' };
262
+ if (cfg.token) headers.Authorization = `Bearer ${cfg.token}`;
263
+ if (body !== undefined) headers['Content-Type'] = 'application/json';
264
+
265
+ let res;
266
+ try {
267
+ res = await fetch(url, {
268
+ method,
269
+ headers,
270
+ body: body !== undefined ? JSON.stringify(body) : undefined,
271
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
272
+ });
273
+ } catch (err) {
274
+ failNetwork(cfg, url, err);
275
+ }
276
+
277
+ const text = await res.text();
278
+ let data = null;
279
+ try {
280
+ data = text ? JSON.parse(text) : null;
281
+ } catch {
282
+ // 非 JSON 响应体,保留原始文本用于报错展示
283
+ }
284
+
285
+ if (!res.ok) {
286
+ failHttp(cfg, res.status, pathname, data, text);
287
+ }
288
+ return data;
289
+ }
290
+
291
+ /* ---------------------------------- 结果格式化 ---------------------------------- */
292
+
293
+ function formatTimestamp(value) {
294
+ if (!value) return '';
295
+ const s = String(value);
296
+ return s.length >= 10 ? s.slice(0, 10) : s;
297
+ }
298
+
299
+ function formatMemoryLine(item) {
300
+ const id = item?.id ?? '?';
301
+ const type = item?.type ?? '?';
302
+ const importance = item?.importance != null ? ` ★${item.importance}` : '';
303
+ const title = item?.title ? ` ${item.title}` : '';
304
+ const tags =
305
+ Array.isArray(item?.tags) && item.tags.length ? ` [${item.tags.join(',')}]` : '';
306
+ const date = formatTimestamp(item?.created_at ?? item?.createdAt);
307
+ return ` #${id} [${type}]${importance}${title}${tags}${date ? ` (${date})` : ''}`;
308
+ }
309
+
310
+ function printMemoryItems(payload, { withMode = false } = {}) {
311
+ const items = Array.isArray(payload?.items) ? payload.items : [];
312
+ const total = payload?.total ?? items.length;
313
+ if (withMode && payload?.mode) console.log(`搜索模式: ${payload.mode}`);
314
+ console.log(`共 ${total} 条,本次显示 ${items.length} 条`);
315
+ if (!items.length) return;
316
+ console.log('');
317
+ for (const item of items) {
318
+ const score = item?.score ?? item?.similarity;
319
+ const scoreText =
320
+ typeof score === 'number' && Number.isFinite(score) ? ` (score ${score.toFixed(3)})` : '';
321
+ console.log(formatMemoryLine(item) + scoreText);
322
+ const content =
323
+ typeof item?.content === 'string' ? item.content.replace(/\s+/g, ' ').trim() : '';
324
+ if (content) {
325
+ console.log(` ${content.length > 80 ? `${content.slice(0, 80)}…` : content}`);
326
+ }
327
+ }
328
+ }
329
+
330
+ function printMemoryDetail(item) {
331
+ if (!item || typeof item !== 'object') {
332
+ console.log(stringify(item ?? null));
333
+ return;
334
+ }
335
+ const fields = [];
336
+ if (item.id !== undefined) fields.push(`id: ${item.id}`);
337
+ if (item.type !== undefined) fields.push(`类型: ${item.type}`);
338
+ if (item.importance !== undefined) fields.push(`重要性: ${item.importance}`);
339
+ if (item.title !== undefined) fields.push(`标题: ${item.title}`);
340
+ if (item.tags !== undefined) {
341
+ fields.push(`标签: ${Array.isArray(item.tags) ? item.tags.join(', ') : item.tags}`);
342
+ }
343
+ if (item.source !== undefined) fields.push(`来源: ${item.source}`);
344
+ const created = item.created_at ?? item.createdAt;
345
+ if (created) fields.push(`创建时间: ${created}`);
346
+ for (const line of fields) console.log(line);
347
+ if (item.content !== undefined) console.log(`\n${item.content}`);
348
+ }
349
+
350
+ function printStatus(data) {
351
+ console.log(`服务版本: ${data?.version ?? '?'}`);
352
+ console.log(`运行时长: ${data?.uptime_s ?? data?.uptimeS ?? '?'} 秒`);
353
+ const memories = data?.memories ?? {};
354
+ console.log(`记忆总数: ${memories.total ?? '?'}`);
355
+ const byType = memories.byType;
356
+ if (Array.isArray(byType)) {
357
+ for (const row of byType) {
358
+ console.log(` - ${row?.type ?? row?.name ?? '?'}: ${row?.count ?? row?.total ?? '?'}`);
359
+ }
360
+ } else if (byType && typeof byType === 'object') {
361
+ for (const [type, count] of Object.entries(byType)) {
362
+ console.log(` - ${type}: ${count}`);
363
+ }
364
+ }
365
+ const entities = data?.entities;
366
+ if (entities != null) {
367
+ const total =
368
+ typeof entities === 'object' && !Array.isArray(entities)
369
+ ? entities.total
370
+ : entities;
371
+ console.log(`实体数量: ${total ?? '?'}`);
372
+ }
373
+ }
374
+
375
+ /* ---------------------------------- 子命令 ---------------------------------- */
376
+
377
+ async function cmdConfig(cfg, sub, rest) {
378
+ const subCmd = sub || 'show';
379
+
380
+ if (subCmd === 'set') {
381
+ const [url, tokenArg] = rest;
382
+ if (!url) {
383
+ fail(
384
+ cfg,
385
+ `用法: ${CLI_NAME} config set <url> <token>\n示例: ${CLI_NAME} config set ${DEFAULT_URL} my-token`
386
+ );
387
+ }
388
+ if (!/^https?:\/\//i.test(url)) {
389
+ fail(cfg, `无效的服务地址: ${url}(应以 http:// 或 https:// 开头)`);
390
+ }
391
+ const existing = readConfigFile();
392
+ const token = tokenArg ?? existing.token ?? '';
393
+ await fsp.mkdir(CONFIG_DIR, { recursive: true });
394
+ await fsp.writeFile(CONFIG_PATH, `${JSON.stringify({ url, token }, null, 2)}\n`, 'utf8');
395
+ if (cfg.jsonMode) {
396
+ console.log(stringify({ configPath: CONFIG_PATH, url, tokenConfigured: Boolean(token) }));
397
+ } else {
398
+ console.log(`已写入配置文件: ${CONFIG_PATH}`);
399
+ console.log(` url: ${url}`);
400
+ console.log(` token: ${maskToken(token)}`);
401
+ }
402
+ return;
403
+ }
404
+
405
+ if (subCmd === 'show') {
406
+ const hasFile = fs.existsSync(CONFIG_PATH);
407
+ const file = readConfigFile();
408
+ if (cfg.jsonMode) {
409
+ console.log(
410
+ stringify({
411
+ configPath: CONFIG_PATH,
412
+ configExists: hasFile,
413
+ url: file.url ?? DEFAULT_URL,
414
+ token: maskToken(file.token),
415
+ })
416
+ );
417
+ return;
418
+ }
419
+ if (!hasFile) {
420
+ console.log(`尚未创建配置文件(未配置): ${CONFIG_PATH}`);
421
+ console.log('');
422
+ console.log(`可运行 \`${CLI_NAME} config set <url> <token>\` 创建配置;`);
423
+ console.log('token 可在 DSH 面板「设置 → 外部访问」或插件设置中查看。');
424
+ console.log(
425
+ `未配置时使用默认地址 ${DEFAULT_URL},也可用环境变量 DSH_MNEME_URL / DSH_MNEME_TOKEN。`
426
+ );
427
+ return;
428
+ }
429
+ console.log(`配置文件: ${CONFIG_PATH}`);
430
+ console.log(` url: ${file.url ?? `(未设置,默认 ${DEFAULT_URL})`}`);
431
+ console.log(` token: ${maskToken(file.token)}`);
432
+ console.log('');
433
+ console.log('配置优先级: --url/--token > 环境变量 DSH_MNEME_URL / DSH_MNEME_TOKEN > 配置文件');
434
+ return;
435
+ }
436
+
437
+ if (subCmd === 'path') {
438
+ console.log(CONFIG_PATH);
439
+ return;
440
+ }
441
+
442
+ fail(cfg, `未知的 config 子命令: ${subCmd}\n可用子命令: set / show / path`);
443
+ }
444
+
445
+ async function cmdStatus(cfg) {
446
+ requireToken(cfg);
447
+ const data = await apiRequest(cfg, 'GET', '/status');
448
+ if (cfg.jsonMode) {
449
+ console.log(stringify(data));
450
+ } else {
451
+ printStatus(data);
452
+ }
453
+ }
454
+
455
+ async function cmdList(cfg, flags) {
456
+ requireToken(cfg);
457
+ const query = {
458
+ type: flagValue(flags, 'type'),
459
+ minImportance: parseIntArg(cfg, flagValue(flags, 'min-importance', 'minImportance'), '--min-importance'),
460
+ source: flagValue(flags, 'source'),
461
+ limit: parseIntArg(cfg, flagValue(flags, 'limit'), '--limit'),
462
+ offset: parseIntArg(cfg, flagValue(flags, 'offset'), '--offset'),
463
+ };
464
+ const data = await apiRequest(cfg, 'GET', '/memories', { query });
465
+ if (cfg.jsonMode) {
466
+ console.log(stringify(data));
467
+ } else {
468
+ printMemoryItems(data);
469
+ }
470
+ }
471
+
472
+ async function cmdSearch(cfg, rest, flags) {
473
+ requireToken(cfg);
474
+ const q = rest[0];
475
+ if (!q) {
476
+ fail(
477
+ cfg,
478
+ `用法: ${CLI_NAME} search <query> [--mode m] [--topk n]\n` +
479
+ `示例: ${CLI_NAME} search "部署流程" --mode vector --topk 5`
480
+ );
481
+ }
482
+ const mode = flagValue(flags, 'mode');
483
+ if (mode !== undefined && !SEARCH_MODES.includes(mode)) {
484
+ fail(cfg, `无效的 --mode: ${mode}(可选: ${SEARCH_MODES.join(' | ')})`);
485
+ }
486
+ const topK = parseIntArg(cfg, flagValue(flags, 'topk', 'top-k', 'topK'), '--topk');
487
+ const data = await apiRequest(cfg, 'GET', '/search', { query: { q, mode, topK } });
488
+ if (cfg.jsonMode) {
489
+ console.log(stringify(data));
490
+ } else {
491
+ printMemoryItems(data, { withMode: true });
492
+ }
493
+ }
494
+
495
+ async function cmdGet(cfg, rest) {
496
+ requireToken(cfg);
497
+ const id = rest[0];
498
+ if (!id) {
499
+ fail(cfg, `用法: ${CLI_NAME} get <id> [--json]`);
500
+ }
501
+ const data = await apiRequest(cfg, 'GET', `/memories/${encodeURIComponent(id)}`);
502
+ if (cfg.jsonMode) {
503
+ console.log(stringify(data));
504
+ } else {
505
+ printMemoryDetail(data);
506
+ }
507
+ }
508
+
509
+ async function cmdAdd(cfg, flags) {
510
+ requireToken(cfg);
511
+ const type = flagValue(flags, 'type');
512
+ const title = flagValue(flags, 'title');
513
+ const content = flagValue(flags, 'content');
514
+ if (!type || !title || !content) {
515
+ fail(
516
+ cfg,
517
+ `用法: ${CLI_NAME} add --type <${MEMORY_TYPES.join('|')}> --title <标题> --content <内容>\n` +
518
+ ` [--importance n] [--tags a,b] [--source s]\n\n` +
519
+ `示例: ${CLI_NAME} add --type decision --title "采用 SQLite" --content "存储层使用 node:sqlite"`
520
+ );
521
+ }
522
+ if (!MEMORY_TYPES.includes(type)) {
523
+ fail(cfg, `无效的 --type: ${type}(可选: ${MEMORY_TYPES.join(' | ')})`);
524
+ }
525
+ const importanceRaw = flagValue(flags, 'importance');
526
+ let importance;
527
+ if (importanceRaw !== undefined) {
528
+ importance = Number(importanceRaw);
529
+ if (!Number.isInteger(importance) || importance < 1 || importance > 5) {
530
+ fail(cfg, `无效的 --importance: ${importanceRaw}(应为 1-5 的整数)`);
531
+ }
532
+ }
533
+ const tagsRaw = flagValue(flags, 'tags');
534
+ const tags =
535
+ tagsRaw !== undefined
536
+ ? tagsRaw.split(',').map((t) => t.trim()).filter(Boolean)
537
+ : undefined;
538
+ const source = flagValue(flags, 'source');
539
+
540
+ const body = { type, title, content };
541
+ if (importance !== undefined) body.importance = importance;
542
+ if (tags) body.tags = tags;
543
+ if (source) body.source = source;
544
+
545
+ const data = await apiRequest(cfg, 'POST', '/memories', { body });
546
+ if (cfg.jsonMode) {
547
+ console.log(stringify(data));
548
+ } else {
549
+ console.log('已添加记忆:');
550
+ printMemoryDetail(data);
551
+ }
552
+ }
553
+
554
+ async function cmdDelete(cfg, rest) {
555
+ requireToken(cfg);
556
+ const id = rest[0];
557
+ if (!id) {
558
+ fail(cfg, `用法: ${CLI_NAME} delete <id>`);
559
+ }
560
+ const data = await apiRequest(cfg, 'DELETE', `/memories/${encodeURIComponent(id)}`);
561
+ if (cfg.jsonMode) {
562
+ console.log(stringify(data));
563
+ } else {
564
+ console.log(`已删除记忆 ${id}`);
565
+ }
566
+ }
567
+
568
+ function formatBytes(bytes) {
569
+ if (typeof bytes !== 'number' || !Number.isFinite(bytes)) return '?';
570
+ const mb = bytes / (1024 * 1024);
571
+ if (mb >= 1) return `${mb.toFixed(1)} MB`;
572
+ return `${(bytes / 1024).toFixed(1)} KB`;
573
+ }
574
+
575
+ function printReclaim(report, { applied }) {
576
+ const planned = report?.planned ?? {};
577
+ const cleared = report?.cleared ?? {};
578
+ const columnBytes = report?.column_bytes ?? {};
579
+ const size = report?.size ?? {};
580
+ console.log(`存储无损回收(${applied ? '已执行' : 'dry-run,未改动任何数据'})`);
581
+ console.log(` 输入快照保留窗口: ${report?.olderThanDays ?? '?'} 天(cutoff ${report?.cutoff ?? '?'})`);
582
+ const rows = (o) => `dream_runs.input ${o.dream_run_inputs ?? 0} 行 / 归档行向量 ${o.archived_embeddings ?? 0} 行`;
583
+ console.log(` ${applied ? '已清理' : '将清理'}: ${rows(applied ? cleared : planned)}`);
584
+ console.log(
585
+ ` 列文本大小(上界,非回收量): ${formatBytes(columnBytes.dream_run_inputs)} / ${formatBytes(columnBytes.archived_embeddings)}`
586
+ );
587
+ if (!applied) {
588
+ console.log(
589
+ ` 库文件: ${formatBytes(size.before_bytes)}(空闲页 ${size.freelist_pages ?? '?'} 页,可立刻回收约 ${formatBytes(size.freelist_bytes)})`
590
+ );
591
+ console.log('');
592
+ console.log(' 上面是 dry-run 的数字。确认后执行:');
593
+ console.log(` ${CLI_NAME} reclaim --apply --vacuum`);
594
+ return;
595
+ }
596
+ const freed =
597
+ typeof size.before_bytes === 'number' && typeof size.after_bytes === 'number'
598
+ ? size.before_bytes - size.after_bytes
599
+ : null;
600
+ if (report?.vacuum?.error) {
601
+ console.log(` VACUUM: 失败(${String(report.vacuum.error).slice(0, 120)})`);
602
+ console.log(' 清理已经完成且不可逆,文件暂时不会变小;库多半被别的进程占着锁,');
603
+ console.log(' 稍后重跑一次 `reclaim --apply --vacuum` 即可(清理是幂等的)。');
604
+ } else {
605
+ console.log(
606
+ ` VACUUM: ${report?.vacuum?.ran ? `已跑(${report.vacuum.duration_ms ?? '?'} ms)` : '未跑(未带 --vacuum,文件不会变小)'}`
607
+ );
608
+ }
609
+ console.log(
610
+ ` 库文件: ${formatBytes(size.before_bytes)} → ${formatBytes(size.after_bytes)}` +
611
+ (freed !== null && freed > 0 ? `(释放 ${formatBytes(freed)})` : '')
612
+ );
613
+ console.log(` 耗时: ${report?.duration_ms ?? '?'} ms`);
614
+ if (report?.receipt) console.log(` 回执: llm_audit_logs #${report.receipt}`);
615
+ }
616
+
617
+ async function cmdReclaim(cfg, flags) {
618
+ requireToken(cfg);
619
+ const applied = flagBool(flags, 'apply');
620
+ const vacuum = flagBool(flags, 'vacuum');
621
+ if (vacuum && !applied) {
622
+ fail(
623
+ cfg,
624
+ `--vacuum 需要配 --apply:dry-run 不改数据,也就没有可回收的页。\n` +
625
+ `先看数字,再执行:${CLI_NAME} reclaim --apply --vacuum`
626
+ );
627
+ }
628
+ const olderThanDays = parseIntArg(cfg, flagValue(flags, 'older-than', 'olderThanDays'), '--older-than');
629
+ const body = { dryRun: !applied };
630
+ if (applied) {
631
+ // 服务端要求显式确认:这两步不可逆,缺 confirm 只会拿回一份 dry-run 报告。
632
+ body.confirm = true;
633
+ }
634
+ if (olderThanDays !== undefined) body.olderThanDays = olderThanDays;
635
+ if (vacuum) body.vacuum = true;
636
+ const data = await apiRequest(cfg, 'POST', '/maintenance/reclaim', { body });
637
+ if (cfg.jsonMode) {
638
+ console.log(stringify(data));
639
+ } else {
640
+ printReclaim(data, { applied });
641
+ }
642
+ }
643
+
644
+ /* ---------------------------------- 入口 ---------------------------------- */
645
+ async function main(argv) {
646
+ const { positionals, flags } = parseArgv(argv);
647
+ const cmd = positionals[0];
648
+ const rest = positionals.slice(1);
649
+
650
+ if (!cmd || cmd === '-h' || cmd === '--help' || cmd === 'help') {
651
+ console.log(USAGE);
652
+ return;
653
+ }
654
+ if (cmd === '-V' || cmd === '--version' || cmd === 'version') {
655
+ console.log(PKG_VERSION);
656
+ return;
657
+ }
658
+
659
+ const cfg = resolveConfig(flags);
660
+ cfg.jsonMode = flagBool(flags, 'json');
661
+
662
+ switch (cmd) {
663
+ case 'config':
664
+ return cmdConfig(cfg, rest[0], rest.slice(1));
665
+ case 'status':
666
+ return cmdStatus(cfg);
667
+ case 'list':
668
+ case 'ls':
669
+ return cmdList(cfg, flags);
670
+ case 'search':
671
+ return cmdSearch(cfg, rest, flags);
672
+ case 'get':
673
+ return cmdGet(cfg, rest);
674
+ case 'add':
675
+ return cmdAdd(cfg, flags);
676
+ case 'delete':
677
+ case 'rm':
678
+ return cmdDelete(cfg, rest);
679
+ case 'reclaim':
680
+ return cmdReclaim(cfg, flags);
681
+ default:
682
+ fail(cfg, `未知命令: ${cmd}\n运行 \`${CLI_NAME} --help\` 查看帮助。`);
683
+ }
684
+ }
685
+
686
+ main(process.argv.slice(2)).catch((err) => {
687
+ console.error(err?.stack ?? String(err));
688
+ process.exit(1);
689
+ });