@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
@@ -1,316 +1,506 @@
1
- // Standalone HTTP API (v0.7.12): a plain node:http server for ecosystem
2
- // integrations that live outside the DSH host and cannot reach the plugin's
3
- // internal webServer routes (/api/dsh-mneme/*). Mirrors the JSON semantics of
4
- // those routes but with mandatory Bearer-token auth on everything except
5
- // GET /health, so the store can be exposed safely on loopback.
6
- //
7
- // Security: the default bind host is 127.0.0.1. Pointing externalApiHost at a
8
- // non-loopback address exposes the whole memory store to the network — that is
9
- // the operator's explicit responsibility (documented in README).
10
- import { createServer } from "node:http";
11
- import { randomBytes, timingSafeEqual } from "node:crypto";
12
- import { TYPES } from "./store.js";
13
-
14
- const DEFAULT_PORT = 8790;
15
- const DEFAULT_HOST = "127.0.0.1";
16
- // Hardcoded release version (package.json is bumped at publish time and may
17
- // lag the code that ships in between).
18
- const VERSION = "0.7.12";
19
- const MAX_PORT_ATTEMPTS = 20;
20
-
21
- /**
22
- * Listen with automatic EADDRINUSE recovery. Tries the configured port, then
23
- * the next MAX_PORT_ATTEMPTS-1 ports, and finally falls back to port 0 so the
24
- * OS assigns a free port. Multiple DSH profiles/instances sharing the default
25
- * port no longer leave the standalone API permanently unavailable.
26
- */
27
- function listenWithRetry(server, startPort, host, logger) {
28
- return new Promise((resolve, reject) => {
29
- let attempt = 0;
30
- const tryListen = (port) => {
31
- const onListening = () => {
32
- server.off("error", onError);
33
- const address = server.address();
34
- resolve(address && typeof address === "object" ? address.port : port);
35
- };
36
- const onError = (error) => {
37
- server.off("listening", onListening);
38
- if (error?.code === "EADDRINUSE" && attempt < MAX_PORT_ATTEMPTS - 1) {
39
- attempt++;
40
- const next = startPort + attempt;
41
- logger?.warn?.(`[dsh-mneme] standalone API port ${port} in use, retrying ${next}`);
42
- tryListen(next);
43
- return;
44
- }
45
- if (error?.code === "EADDRINUSE") {
46
- logger?.warn?.(`[dsh-mneme] standalone API port ${port} still in use, falling back to OS-assigned port`);
47
- tryListen(0);
48
- return;
49
- }
50
- reject(error);
51
- };
52
- server.once("listening", onListening);
53
- server.once("error", onError);
54
- server.listen(port, host);
55
- };
56
- tryListen(startPort);
57
- });
58
- }
59
-
60
- function sendJson(res, status, payload) {
61
- res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
62
- res.end(JSON.stringify(payload));
63
- }
64
-
65
- /** True when the request carries the configured token. */
66
- function isAuthorized(req, apiToken) {
67
- const raw = req.headers?.authorization ?? req.headers?.["x-dsh-mneme-token"] ?? "";
68
- const token = raw.startsWith("Bearer ") ? raw.slice(7).trim() : raw.trim();
69
- if (token === "" || token.length !== apiToken.length) return false;
70
- // Constant-time comparison: no timing oracle on the token.
71
- return timingSafeEqual(Buffer.from(token), Buffer.from(apiToken));
72
- }
73
-
74
- /** Collect the request body as text (tolerant of transport errors). */
75
- function readBody(req) {
76
- return new Promise((resolve) => {
77
- let body = "";
78
- req.on("data", (chunk) => { body += chunk; });
79
- req.on("end", () => resolve(body));
80
- req.on("error", () => resolve(""));
81
- });
82
- }
83
-
84
- /**
85
- * Create (and start) the standalone API server.
86
- * Accepts { service, store, config, logger, settings, port, host }:
87
- * - token: persisted settings kv "external_api" wins; auto-generated
88
- * (crypto.randomBytes(24).toString("base64url")) and persisted when empty.
89
- * - port: explicit arg > persisted settings > config.externalApiPort > 8790.
90
- * - host: explicit arg > config.externalApiHost > "127.0.0.1".
91
- * Returns { server, port, host, token, ready }: `port` is the effective bound
92
- * port (updated to the OS-assigned one after `ready` resolves when asked to
93
- * bind port 0), `ready` resolves once listening and rejects if the bind fails.
94
- */
95
- export function createStandaloneApi({ service, store, config = {}, logger, settings, port, host }) {
96
- const persisted = settings?.getExternalApi?.() ?? {};
97
-
98
- let token = typeof persisted.token === "string" ? persisted.token : "";
99
- if (!token) {
100
- token = randomBytes(24).toString("base64url");
101
- // Persist only the token; enabled/port keys stay as they are (merge).
102
- try {
103
- settings?.setExternalApi?.({ token });
104
- } catch (error) {
105
- logger?.warn?.(`[dsh-mneme] standalone API token persistence failed: ${String(error)}`);
106
- }
107
- }
108
-
109
- // Persisted host (set from the panel) wins over the bundle config, same
110
- // precedence as port; the explicit argument still wins over both.
111
- const boundHost = host
112
- ?? (typeof persisted.host === "string" && persisted.host ? persisted.host : undefined)
113
- ?? config.externalApiHost
114
- ?? DEFAULT_HOST;
115
- const persistedPort = Number(persisted.port);
116
- const boundPort = port
117
- ?? (Number.isInteger(persistedPort) && persistedPort > 0 ? persistedPort : undefined)
118
- ?? config.externalApiPort
119
- ?? DEFAULT_PORT;
120
-
121
- const server = createServer((req, res) => {
122
- try {
123
- const url = new URL(req.url ?? "/", "http://localhost");
124
- const pathname = url.pathname;
125
-
126
- // Health is the single unauthenticated probe (monitor checks).
127
- if (req.method === "GET" && pathname === "/health") {
128
- sendJson(res, 200, { ok: true });
129
- return;
130
- }
131
-
132
- // Everything else requires the Bearer token.
133
- if (!isAuthorized(req, token)) {
134
- sendJson(res, 401, { error: "unauthorized" });
135
- return;
136
- }
137
-
138
- // --- GET /status: version + store shape + uptime -----------------------
139
- if (req.method === "GET" && pathname === "/status") {
140
- const byType = {};
141
- for (const type of TYPES) byType[type] = service.count(type);
142
- let entities = 0;
143
- try {
144
- entities = store.db.prepare("SELECT count(*) AS c FROM entities").get().c;
145
- } catch { /* entities storage unavailable → 0 */ }
146
- sendJson(res, 200, {
147
- version: VERSION,
148
- memories: { total: service.count(), byType },
149
- entities,
150
- uptime_s: Math.floor(process.uptime())
151
- });
152
- return;
153
- }
154
-
155
- // --- GET /profile: user self-description -------------------------------
156
- if (req.method === "GET" && pathname === "/profile") {
157
- sendJson(res, 200, { profile: settings?.getProfile?.() ?? "" });
158
- return;
159
- }
160
-
161
- // --- GET /rules: agent behavior rules -----------------------------------
162
- if (req.method === "GET" && pathname === "/rules") {
163
- sendJson(res, 200, { rules: settings?.getRules?.() ?? [] });
164
- return;
165
- }
166
-
167
- // --- GET /memories: paged + filtered list (same semantics as the
168
- // internal /api/dsh-mneme/list) ------------------------------------
169
- if (req.method === "GET" && pathname === "/memories") {
170
- const type = url.searchParams.get("type") ?? undefined;
171
- const limit = Number(url.searchParams.get("limit") ?? 50);
172
- const offset = Number(url.searchParams.get("offset") ?? 0);
173
- const order = url.searchParams.get("order") ?? undefined;
174
- const minRaw = url.searchParams.get("minImportance");
175
- const minImportance = minRaw !== null && minRaw !== "" && !Number.isNaN(Number(minRaw))
176
- ? Number(minRaw)
177
- : undefined;
178
- const source = url.searchParams.get("source") || undefined;
179
- const items = service.toApiList(service.list({ type, limit, offset, order, minImportance, source }));
180
- // Total honors the same filters so pager math stays correct.
181
- sendJson(res, 200, { items, total: service.count(type, { minImportance, source }) });
182
- return;
183
- }
184
-
185
- // --- GET/DELETE /memories/:id ------------------------------------------
186
- const idMatch = pathname.match(/^\/memories\/([^/]+)$/);
187
- if (idMatch) {
188
- let id = idMatch[1];
189
- try { id = decodeURIComponent(id); } catch { /* keep raw */ }
190
- if (req.method === "GET") {
191
- const row = service.getById(id);
192
- if (!row) {
193
- sendJson(res, 404, { error: "not-found" });
194
- return;
195
- }
196
- sendJson(res, 200, service.toApiList([row])[0]);
197
- return;
198
- }
199
- if (req.method === "DELETE") {
200
- // store.remove deletes silently — precheck for a distinguishable 404.
201
- if (!service.getById(id)) {
202
- sendJson(res, 404, { error: "not-found" });
203
- return;
204
- }
205
- service.remove(id);
206
- sendJson(res, 200, { ok: true });
207
- return;
208
- }
209
- sendJson(res, 404, { error: "not-found" });
210
- return;
211
- }
212
-
213
- // --- POST /memories: save with title-dedupe (safer than raw save) ------
214
- if (req.method === "POST" && pathname === "/memories") {
215
- void readBody(req).then((text) => {
216
- let body;
217
- try {
218
- body = JSON.parse(text || "{}");
219
- } catch {
220
- sendJson(res, 400, { error: "invalid-json" });
221
- return;
222
- }
223
- if (body === null || typeof body !== "object" || Array.isArray(body)) {
224
- sendJson(res, 400, { error: "invalid-body" });
225
- return;
226
- }
227
- // Pre-validate what store.save would throw on, so clients get a
228
- // clean 400 instead of a leaked SQLite error.
229
- if (!TYPES.has(body.type)) {
230
- sendJson(res, 400, { error: "invalid-type" });
231
- return;
232
- }
233
- if (typeof body.title !== "string" || !body.title.trim()) {
234
- sendJson(res, 400, { error: "missing-title" });
235
- return;
236
- }
237
- if (typeof body.content !== "string") {
238
- sendJson(res, 400, { error: "missing-content" });
239
- return;
240
- }
241
- if (body.tags !== undefined && !Array.isArray(body.tags)) {
242
- sendJson(res, 400, { error: "tags-must-be-an-array" });
243
- return;
244
- }
245
- try {
246
- const { action, memory } = service.saveWithDedupe({
247
- type: body.type,
248
- title: body.title,
249
- content: body.content,
250
- importance: body.importance,
251
- tags: body.tags,
252
- source: body.source
253
- });
254
- sendJson(res, action === "created" ? 201 : 200, service.toApiList([memory])[0]);
255
- } catch (error) {
256
- logger?.warn?.(`[dsh-mneme] standalone API save failed: ${String(error)}`);
257
- sendJson(res, 500, { error: "internal" });
258
- }
259
- });
260
- return;
261
- }
262
-
263
- // --- GET /search: unified recall pipeline (keyword + vector + BM25) ----
264
- if (req.method === "GET" && pathname === "/search") {
265
- const q = url.searchParams.get("q") ?? "";
266
- const limit = Number(url.searchParams.get("topK") ?? url.searchParams.get("limit") ?? 20);
267
- const mode = url.searchParams.get("mode") ?? "auto";
268
- const rerank = url.searchParams.get("rerank") !== "false";
269
- const query = q.trim();
270
- if (!query) {
271
- sendJson(res, 200, { items: [], mode: "keyword" });
272
- return;
273
- }
274
- // Any vector/rerank failure degrades to keyword inside searchMemories.
275
- void Promise.resolve(
276
- service.searchMemories(query, { mode, topK: limit, useRerank: rerank })
277
- ).then((rows) => {
278
- const used = rows.some((m) => m.vector === true) ? "vector" : "keyword";
279
- sendJson(res, 200, { items: service.toApiList(rows), mode: used });
280
- }).catch(() => {
281
- sendJson(res, 200, { items: service.toApiList(service.search(query, { limit })), mode: "keyword" });
282
- });
283
- return;
284
- }
285
-
286
- sendJson(res, 404, { error: "not-found" });
287
- } catch {
288
- sendJson(res, 500, { error: "internal" });
289
- }
290
- });
291
-
292
- // A permanent error listener keeps an EADDRINUSE / runtime socket error from
293
- // crashing the host process; `ready` still surfaces the first bind failure.
294
- server.on("error", (error) => {
295
- logger?.warn?.(`[dsh-mneme] standalone API error: ${String(error)}`);
296
- });
297
- const ready = new Promise((resolve, reject) => {
298
- // listening handled by listenWithRetry
299
- listenWithRetry(server, boundPort, boundHost, logger).then(resolve, reject);
300
- });
301
- // server.listen is called inside listenWithRetry
302
- ready.then(() => {
303
- const address = server.address();
304
- if (address && typeof address === "object") {
305
- logger?.info?.(`[dsh-mneme] standalone API listening on http://${address.address}:${address.port}`);
306
- }
307
- }).catch(() => { /* already logged by the error handler above */ });
308
-
309
- const api = { server, port: boundPort, host: boundHost, token, ready };
310
- // After the OS assigns the real port (bind port 0), reflect it for callers.
311
- ready.then(() => {
312
- const address = server.address();
313
- if (address && typeof address === "object") api.port = address.port;
314
- }).catch(() => { /* bind failed: port stays as configured */ });
315
- return api;
316
- }
1
+ // Standalone HTTP API (v0.7.12): a plain node:http server for ecosystem
2
+ // integrations that live outside the DSH host and cannot reach the plugin's
3
+ // internal webServer routes (/api/dsh-mneme/*). Mirrors the JSON semantics of
4
+ // those routes but with mandatory Bearer-token auth on everything except
5
+ // GET /health, so the store can be exposed safely on loopback.
6
+ //
7
+ // #181 (MCP stdio server, bin/dsh-mneme-mcp.mjs) rides on these routes as its
8
+ // data plane: the six-tool surface (memory_save/search/list/get/update/delete)
9
+ // is fully served here — PUT /memories/:id, the save passthrough fields
10
+ // (sensitivity / occurred_at / explicit scope) and the list/search archived +
11
+ // occurred-window filters exist for that parity, with tool-identical semantics.
12
+ //
13
+ // Security: the default bind host is 127.0.0.1. Pointing externalApiHost at a
14
+ // non-loopback address exposes the whole memory store to the network — that is
15
+ // the operator's explicit responsibility (documented in README).
16
+ import { createServer } from "node:http";
17
+ import { randomBytes, timingSafeEqual } from "node:crypto";
18
+ import { TYPES } from "./store.js";
19
+ import { bootstrapFromDirectory } from "./bootstrap.js";
20
+
21
+ const DEFAULT_PORT = 8790;
22
+ const DEFAULT_HOST = "127.0.0.1";
23
+ // Hardcoded release version (package.json is bumped at publish time and may
24
+ // lag the code that ships in between).
25
+ const VERSION = "0.7.12";
26
+ const MAX_PORT_ATTEMPTS = 20;
27
+
28
+ /**
29
+ * Listen with automatic EADDRINUSE recovery. Tries the configured port, then
30
+ * the next MAX_PORT_ATTEMPTS-1 ports, and finally falls back to port 0 so the
31
+ * OS assigns a free port. Multiple DSH profiles/instances sharing the default
32
+ * port no longer leave the standalone API permanently unavailable.
33
+ */
34
+ function listenWithRetry(server, startPort, host, logger) {
35
+ return new Promise((resolve, reject) => {
36
+ let attempt = 0;
37
+ const tryListen = (port) => {
38
+ const onListening = () => {
39
+ server.off("error", onError);
40
+ const address = server.address();
41
+ resolve(address && typeof address === "object" ? address.port : port);
42
+ };
43
+ const onError = (error) => {
44
+ server.off("listening", onListening);
45
+ if (error?.code === "EADDRINUSE" && attempt < MAX_PORT_ATTEMPTS - 1) {
46
+ attempt++;
47
+ const next = startPort + attempt;
48
+ logger?.warn?.(`[dsh-mneme] standalone API port ${port} in use, retrying ${next}`);
49
+ tryListen(next);
50
+ return;
51
+ }
52
+ if (error?.code === "EADDRINUSE") {
53
+ logger?.warn?.(`[dsh-mneme] standalone API port ${port} still in use, falling back to OS-assigned port`);
54
+ tryListen(0);
55
+ return;
56
+ }
57
+ reject(error);
58
+ };
59
+ server.once("listening", onListening);
60
+ server.once("error", onError);
61
+ server.listen(port, host);
62
+ };
63
+ tryListen(startPort);
64
+ });
65
+ }
66
+
67
+ function sendJson(res, status, payload) {
68
+ res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
69
+ res.end(JSON.stringify(payload));
70
+ }
71
+
72
+ /** True when the request carries the configured token. */
73
+ function isAuthorized(req, apiToken) {
74
+ const raw = req.headers?.authorization ?? req.headers?.["x-dsh-mneme-token"] ?? "";
75
+ const token = raw.startsWith("Bearer ") ? raw.slice(7).trim() : raw.trim();
76
+ if (token === "" || token.length !== apiToken.length) return false;
77
+ // Constant-time comparison: no timing oracle on the token.
78
+ return timingSafeEqual(Buffer.from(token), Buffer.from(apiToken));
79
+ }
80
+
81
+ /** Collect the request body as text (tolerant of transport errors). */
82
+ function readBody(req) {
83
+ return new Promise((resolve) => {
84
+ let body = "";
85
+ req.on("data", (chunk) => { body += chunk; });
86
+ req.on("end", () => resolve(body));
87
+ req.on("error", () => resolve(""));
88
+ });
89
+ }
90
+
91
+ /**
92
+ * PUT /memories/:id 的请求体处理(模块级函数便于在调用点被 try/catch 包住:
93
+ * service 抛错绝不能变成未处理拒绝或悬着不回的请求)。校验与内部
94
+ * /api/dsh-mneme/update 同风格:字段出现就必须合法,宁 400 不静默纠正;
95
+ * content 改写按 human_override 入档;scope 修正归一化在 service 层做
96
+ * (null=放宽到全局,字符串=收窄/改标),审计 actor 记 "tool"。
97
+ */
98
+ async function handlePutBody(res, service, logger, id, text) {
99
+ let body;
100
+ try {
101
+ body = JSON.parse(text || "{}");
102
+ } catch {
103
+ sendJson(res, 400, { error: "invalid-json" });
104
+ return;
105
+ }
106
+ if (body === null || typeof body !== "object" || Array.isArray(body)) {
107
+ sendJson(res, 400, { error: "invalid-body" });
108
+ return;
109
+ }
110
+ const patch = {};
111
+ if (body.title !== undefined) {
112
+ if (typeof body.title !== "string" || !body.title.trim()) {
113
+ sendJson(res, 400, { error: "invalid-title" });
114
+ return;
115
+ }
116
+ patch.title = body.title.trim();
117
+ }
118
+ if (body.content !== undefined) {
119
+ if (typeof body.content !== "string" || !body.content.trim()) {
120
+ sendJson(res, 400, { error: "invalid-content" });
121
+ return;
122
+ }
123
+ patch.content = body.content.trim();
124
+ }
125
+ if (body.type !== undefined) {
126
+ if (!TYPES.has(body.type)) {
127
+ sendJson(res, 400, { error: "invalid-type" });
128
+ return;
129
+ }
130
+ patch.type = body.type;
131
+ }
132
+ if (body.importance !== undefined) {
133
+ if (!Number.isInteger(body.importance) || body.importance < 1 || body.importance > 5) {
134
+ sendJson(res, 400, { error: "invalid-importance" });
135
+ return;
136
+ }
137
+ patch.importance = body.importance;
138
+ }
139
+ if (body.tags !== undefined) {
140
+ if (!Array.isArray(body.tags) || !body.tags.every((t) => typeof t === "string")) {
141
+ sendJson(res, 400, { error: "invalid-tags" });
142
+ return;
143
+ }
144
+ patch.tags = body.tags;
145
+ }
146
+ if (body.agent_scope !== undefined && body.agent_scope !== null && typeof body.agent_scope !== "string") {
147
+ sendJson(res, 400, { error: "invalid-agent-scope" });
148
+ return;
149
+ }
150
+ if (body.workspace_scope !== undefined && body.workspace_scope !== null && typeof body.workspace_scope !== "string") {
151
+ sendJson(res, 400, { error: "invalid-workspace-scope" });
152
+ return;
153
+ }
154
+ if (body.agent_scope !== undefined) patch.agent_scope = body.agent_scope;
155
+ if (body.workspace_scope !== undefined) patch.workspace_scope = body.workspace_scope;
156
+ if (body.reason !== undefined && (typeof body.reason !== "string" || !body.reason.trim())) {
157
+ sendJson(res, 400, { error: "invalid-reason" });
158
+ return;
159
+ }
160
+ if (Object.keys(patch).length === 0) {
161
+ sendJson(res, 400, { error: "no-fields" });
162
+ return;
163
+ }
164
+ const existing = service.getById(id);
165
+ if (!existing) {
166
+ sendJson(res, 404, { error: "not-found" });
167
+ return;
168
+ }
169
+ if (patch.type === "document" && existing.type !== "document") {
170
+ // #230 写入权分离:type 不许改入 document(铸造口唯一),干净 400。
171
+ sendJson(res, 400, { error: "document-requires-register" });
172
+ return;
173
+ }
174
+ // 内容被改写时旧版本先入档(human_override),与内部面板写路径一致。
175
+ if (patch.content !== undefined && patch.content !== existing.content) {
176
+ const history = Array.isArray(existing.content_history) ? existing.content_history : [];
177
+ patch.content_history = [
178
+ { content: existing.content ?? "", source: "human_override", updated_at: new Date().toISOString() },
179
+ ...history
180
+ ].slice(0, 20);
181
+ }
182
+ service.update(id, patch, {
183
+ actor: "tool",
184
+ ...(typeof body.reason === "string" && body.reason.trim() ? { query: body.reason.trim() } : {})
185
+ });
186
+ sendJson(res, 200, { memory: service.toApiList([service.getById(id)])[0] });
187
+ }
188
+
189
+ /**
190
+ * Create (and start) the standalone API server.
191
+ * Accepts { service, store, config, logger, settings, port, host }:
192
+ * - token: persisted settings kv "external_api" wins; auto-generated
193
+ * (crypto.randomBytes(24).toString("base64url")) and persisted when empty.
194
+ * - port: explicit arg > persisted settings > config.externalApiPort > 8790.
195
+ * - host: explicit arg > config.externalApiHost > "127.0.0.1".
196
+ * Returns { server, port, host, token, ready }: `port` is the effective bound
197
+ * port (updated to the OS-assigned one after `ready` resolves when asked to
198
+ * bind port 0), `ready` resolves once listening and rejects if the bind fails.
199
+ */
200
+ export function createStandaloneApi({ service, store, config = {}, logger, settings, port, host }) {
201
+ const persisted = settings?.getExternalApi?.() ?? {};
202
+
203
+ let token = typeof persisted.token === "string" ? persisted.token : "";
204
+ if (!token) {
205
+ token = randomBytes(24).toString("base64url");
206
+ // Persist only the token; enabled/port keys stay as they are (merge).
207
+ try {
208
+ settings?.setExternalApi?.({ token });
209
+ } catch (error) {
210
+ logger?.warn?.(`[dsh-mneme] standalone API token persistence failed: ${String(error)}`);
211
+ }
212
+ }
213
+
214
+ // Persisted host (set from the panel) wins over the bundle config, same
215
+ // precedence as port; the explicit argument still wins over both.
216
+ const boundHost = host
217
+ ?? (typeof persisted.host === "string" && persisted.host ? persisted.host : undefined)
218
+ ?? config.externalApiHost
219
+ ?? DEFAULT_HOST;
220
+ const persistedPort = Number(persisted.port);
221
+ const boundPort = port
222
+ ?? (Number.isInteger(persistedPort) && persistedPort > 0 ? persistedPort : undefined)
223
+ ?? config.externalApiPort
224
+ ?? DEFAULT_PORT;
225
+
226
+ const server = createServer((req, res) => {
227
+ try {
228
+ const url = new URL(req.url ?? "/", "http://localhost");
229
+ const pathname = url.pathname;
230
+
231
+ // Health is the single unauthenticated probe (monitor checks).
232
+ if (req.method === "GET" && pathname === "/health") {
233
+ sendJson(res, 200, { ok: true });
234
+ return;
235
+ }
236
+
237
+ // Everything else requires the Bearer token.
238
+ if (!isAuthorized(req, token)) {
239
+ sendJson(res, 401, { error: "unauthorized" });
240
+ return;
241
+ }
242
+
243
+ // --- GET /status: version + store shape + uptime -----------------------
244
+ if (req.method === "GET" && pathname === "/status") {
245
+ const byType = {};
246
+ for (const type of TYPES) byType[type] = service.count(type);
247
+ let entities = 0;
248
+ try {
249
+ entities = store.db.prepare("SELECT count(*) AS c FROM entities").get().c;
250
+ } catch { /* entities storage unavailable → 0 */ }
251
+ sendJson(res, 200, {
252
+ version: VERSION,
253
+ memories: { total: service.count(), byType },
254
+ entities,
255
+ uptime_s: Math.floor(process.uptime())
256
+ });
257
+ return;
258
+ }
259
+
260
+ // --- GET /profile: user self-description -------------------------------
261
+ if (req.method === "GET" && pathname === "/profile") {
262
+ sendJson(res, 200, { profile: settings?.getProfile?.() ?? "" });
263
+ return;
264
+ }
265
+
266
+ // --- GET /rules: agent behavior rules -----------------------------------
267
+ if (req.method === "GET" && pathname === "/rules") {
268
+ sendJson(res, 200, { rules: settings?.getRules?.() ?? [] });
269
+ return;
270
+ }
271
+
272
+ // --- GET /memories: paged + filtered list (same semantics as the
273
+ // internal /api/dsh-mneme/list) ------------------------------------
274
+ if (req.method === "GET" && pathname === "/memories") {
275
+ const type = url.searchParams.get("type") ?? undefined;
276
+ const limit = Number(url.searchParams.get("limit") ?? 50);
277
+ const offset = Number(url.searchParams.get("offset") ?? 0);
278
+ const order = url.searchParams.get("order") ?? undefined;
279
+ const minRaw = url.searchParams.get("minImportance");
280
+ const minImportance = minRaw !== null && minRaw !== "" && !Number.isNaN(Number(minRaw))
281
+ ? Number(minRaw)
282
+ : undefined;
283
+ const source = url.searchParams.get("source") || undefined;
284
+ // include_archived + occurred 时间窗:与 memory_list 工具同口径(工具
285
+ // 面六件套经 8790 全量可用,#181);缺省行为与既有调用方逐字节一致。
286
+ const includeArchived = url.searchParams.get("include_archived") === "true";
287
+ const occurredFrom = url.searchParams.get("occurred_from") ?? undefined;
288
+ const occurredTo = url.searchParams.get("occurred_to") ?? undefined;
289
+ const listFilters = { includeArchived, ...(occurredFrom ? { occurredFrom } : {}), ...(occurredTo ? { occurredTo } : {}) };
290
+ const items = service.toApiList(service.list({ type, limit, offset, order, minImportance, source, ...listFilters }));
291
+ // Total honors the same filters so pager math stays correct.
292
+ sendJson(res, 200, { items, total: service.count(type, { minImportance, source, ...listFilters }) });
293
+ return;
294
+ }
295
+
296
+ // --- GET/PUT/DELETE /memories/:id --------------------------------------
297
+ const idMatch = pathname.match(/^\/memories\/([^/]+)$/);
298
+ if (idMatch) {
299
+ let id = idMatch[1];
300
+ try { id = decodeURIComponent(id); } catch { /* keep raw */ }
301
+ if (req.method === "GET") {
302
+ const row = service.getById(id);
303
+ if (!row) {
304
+ sendJson(res, 404, { error: "not-found" });
305
+ return;
306
+ }
307
+ sendJson(res, 200, service.toApiList([row])[0]);
308
+ return;
309
+ }
310
+ if (req.method === "DELETE") {
311
+ // store.remove deletes silently — precheck for a distinguishable 404.
312
+ if (!service.getById(id)) {
313
+ sendJson(res, 404, { error: "not-found" });
314
+ return;
315
+ }
316
+ service.remove(id);
317
+ sendJson(res, 200, { ok: true });
318
+ return;
319
+ }
320
+ // --- PUT: field patch(memory_update 工具的外部通道,#181)。字段校验
321
+ // 与内部 /api/dsh-mneme/update 同风格:字段出现就必须合法,宁 400 不静默
322
+ // 纠正;content 改写按 human_override 入档;scope 修正归一化在 service
323
+ // 层做(null=放宽到全局,字符串=收窄/改标),审计 actor 记 "tool"。
324
+ // 整个异步回调套 try/catch:service 抛错不能变成未处理拒绝(Node 默认
325
+ // 策略下会终止宿主进程)或悬着不回的请求(外层同步 try 捕不到这里)。
326
+ if (req.method === "PUT") {
327
+ void readBody(req).then(async (text) => {
328
+ try {
329
+ await handlePutBody(res, service, logger, id, text);
330
+ } catch (error) {
331
+ logger?.warn?.(`[dsh-mneme] standalone API update failed: ${String(error)}`);
332
+ sendJson(res, 500, { error: "internal" });
333
+ }
334
+ });
335
+ return;
336
+ }
337
+ sendJson(res, 404, { error: "not-found" });
338
+ return;
339
+ }
340
+
341
+ // --- POST /memories: save with title-dedupe (safer than raw save) ------
342
+ if (req.method === "POST" && pathname === "/memories") {
343
+ void readBody(req).then((text) => {
344
+ let body;
345
+ try {
346
+ body = JSON.parse(text || "{}");
347
+ } catch {
348
+ sendJson(res, 400, { error: "invalid-json" });
349
+ return;
350
+ }
351
+ if (body === null || typeof body !== "object" || Array.isArray(body)) {
352
+ sendJson(res, 400, { error: "invalid-body" });
353
+ return;
354
+ }
355
+ // Pre-validate what store.save would throw on, so clients get a
356
+ // clean 400 instead of a leaked SQLite error.
357
+ if (!TYPES.has(body.type)) {
358
+ sendJson(res, 400, { error: "invalid-type" });
359
+ return;
360
+ }
361
+ if (body.type === "document") {
362
+ // #230 写入权分离:document 行铸造口唯一(registerDocument)。
363
+ // 这里给干净 400,不让它落进 saveWithDedupe 的守卫变 500。
364
+ sendJson(res, 400, { error: "document-requires-register" });
365
+ return;
366
+ }
367
+ if (typeof body.title !== "string" || !body.title.trim()) {
368
+ sendJson(res, 400, { error: "missing-title" });
369
+ return;
370
+ }
371
+ if (typeof body.content !== "string") {
372
+ sendJson(res, 400, { error: "missing-content" });
373
+ return;
374
+ }
375
+ if (body.tags !== undefined && !Array.isArray(body.tags)) {
376
+ sendJson(res, 400, { error: "tags-must-be-an-array" });
377
+ return;
378
+ }
379
+ // memory_save 工具的其余可选字段(#181):sensitivity / occurred_at /
380
+ // 显式 scope。scope 仅收显式声明(standalone API 无会话上下文,自动
381
+ // 标注无从解析,语义与工具的显式参数一致);形状不对宁 400 不静默丢。
382
+ for (const key of ["sensitivity", "occurred_at", "agent_scope", "workspace_scope"]) {
383
+ if (body[key] !== undefined && (typeof body[key] !== "string" || !body[key].trim())) {
384
+ sendJson(res, 400, { error: `invalid-${key.replace(/_/g, "-")}` });
385
+ return;
386
+ }
387
+ }
388
+ try {
389
+ const { action, memory } = service.saveWithDedupe({
390
+ type: body.type,
391
+ title: body.title,
392
+ content: body.content,
393
+ importance: body.importance,
394
+ tags: body.tags,
395
+ source: body.source,
396
+ ...(body.sensitivity !== undefined ? { sensitivity: body.sensitivity } : {}),
397
+ ...(body.occurred_at !== undefined ? { occurred_at: body.occurred_at } : {}),
398
+ ...(body.agent_scope !== undefined ? { agent_scope: body.agent_scope, agent_scope_source: "explicit" } : {}),
399
+ ...(body.workspace_scope !== undefined ? { workspace_scope: body.workspace_scope, workspace_scope_source: "explicit" } : {})
400
+ });
401
+ // action 随行透出(created/merged):memory_save 工具语义对齐所需,
402
+ // 附加键对既有消费方(CLI add 等)向后兼容。
403
+ sendJson(res, action === "created" ? 201 : 200, { ...service.toApiList([memory])[0], action });
404
+ } catch (error) {
405
+ logger?.warn?.(`[dsh-mneme] standalone API save failed: ${String(error)}`);
406
+ sendJson(res, 500, { error: "internal" });
407
+ }
408
+ });
409
+ return;
410
+ }
411
+
412
+ // --- POST /bootstrap: cold-start memories from repo files (#220) -------
413
+ // 显式收 dir(插件没有工作区根目录概念,不猜路径);确定性解析零 LLM;
414
+ // 幂等骑 saveWithDedupe 的 (type, title, scope) 去重 + _overwrite 刷新。
415
+ if (req.method === "POST" && pathname === "/bootstrap") {
416
+ void readBody(req).then((text) => {
417
+ let body;
418
+ try {
419
+ body = JSON.parse(text || "{}");
420
+ } catch {
421
+ sendJson(res, 400, { error: "invalid-json" });
422
+ return;
423
+ }
424
+ if (body === null || typeof body !== "object" || Array.isArray(body)) {
425
+ sendJson(res, 400, { error: "invalid-body" });
426
+ return;
427
+ }
428
+ if (typeof body.dir !== "string" || !body.dir.trim()) {
429
+ sendJson(res, 400, { error: "missing-dir" });
430
+ return;
431
+ }
432
+ bootstrapFromDirectory({ service, dir: body.dir, logger })
433
+ .then((summary) => sendJson(res, 200, summary))
434
+ .catch((error) => {
435
+ if (error?.code) {
436
+ sendJson(res, 400, { error: error.code });
437
+ return;
438
+ }
439
+ logger?.warn?.(`[dsh-mneme] standalone API bootstrap failed: ${String(error)}`);
440
+ sendJson(res, 500, { error: "internal" });
441
+ });
442
+ });
443
+ return;
444
+ }
445
+
446
+ // --- GET /search: unified recall pipeline (keyword + vector + BM25) ----
447
+ if (req.method === "GET" && pathname === "/search") {
448
+ const q = url.searchParams.get("q") ?? "";
449
+ const limit = Number(url.searchParams.get("topK") ?? url.searchParams.get("limit") ?? 20);
450
+ const mode = url.searchParams.get("mode") ?? "auto";
451
+ const rerank = url.searchParams.get("rerank") !== "false";
452
+ const occurredFrom = url.searchParams.get("occurred_from") ?? null;
453
+ const occurredTo = url.searchParams.get("occurred_to") ?? null;
454
+ const query = q.trim();
455
+ if (!query) {
456
+ sendJson(res, 200, { items: [], mode: "keyword" });
457
+ return;
458
+ }
459
+ // Any vector/rerank failure degrades to keyword inside searchMemories.
460
+ void Promise.resolve(
461
+ service.searchMemories(query, {
462
+ mode,
463
+ topK: limit,
464
+ useRerank: rerank,
465
+ ...(occurredFrom !== null || occurredTo !== null ? { occurredFrom, occurredTo } : {})
466
+ })
467
+ ).then((rows) => {
468
+ const used = rows.some((m) => m.vector === true) ? "vector" : "keyword";
469
+ sendJson(res, 200, { items: service.toApiList(rows), mode: used });
470
+ }).catch(() => {
471
+ sendJson(res, 200, { items: service.toApiList(service.search(query, { limit })), mode: "keyword" });
472
+ });
473
+ return;
474
+ }
475
+
476
+ sendJson(res, 404, { error: "not-found" });
477
+ } catch {
478
+ sendJson(res, 500, { error: "internal" });
479
+ }
480
+ });
481
+
482
+ // A permanent error listener keeps an EADDRINUSE / runtime socket error from
483
+ // crashing the host process; `ready` still surfaces the first bind failure.
484
+ server.on("error", (error) => {
485
+ logger?.warn?.(`[dsh-mneme] standalone API error: ${String(error)}`);
486
+ });
487
+ const ready = new Promise((resolve, reject) => {
488
+ // listening handled by listenWithRetry
489
+ listenWithRetry(server, boundPort, boundHost, logger).then(resolve, reject);
490
+ });
491
+ // server.listen is called inside listenWithRetry
492
+ ready.then(() => {
493
+ const address = server.address();
494
+ if (address && typeof address === "object") {
495
+ logger?.info?.(`[dsh-mneme] standalone API listening on http://${address.address}:${address.port}`);
496
+ }
497
+ }).catch(() => { /* already logged by the error handler above */ });
498
+
499
+ const api = { server, port: boundPort, host: boundHost, token, ready };
500
+ // After the OS assigns the real port (bind port 0), reflect it for callers.
501
+ ready.then(() => {
502
+ const address = server.address();
503
+ if (address && typeof address === "object") api.port = address.port;
504
+ }).catch(() => { /* bind failed: port stays as configured */ });
505
+ return api;
506
+ }