@modusensus/dsh-mneme 0.8.3 → 0.8.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (193) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +718 -636
  3. package/bin/cli.mjs +0 -0
  4. package/bin/dsh-mneme-mcp.mjs +502 -0
  5. package/cordis.patch.yml +21 -21
  6. package/lib/api-standalone.js +495 -316
  7. package/lib/api.js +1382 -1316
  8. package/lib/bootstrap.js +211 -0
  9. package/lib/client.js +4475 -4366
  10. package/lib/commands.js +95 -95
  11. package/lib/config.js +533 -510
  12. package/lib/dream/clustering.js +118 -118
  13. package/lib/dream/decisions.js +658 -658
  14. package/lib/dream/narratives.js +44 -0
  15. package/lib/dream/sleep.js +700 -700
  16. package/lib/dream.js +1319 -1216
  17. package/lib/embedding.js +177 -177
  18. package/lib/entities/extractor.js +249 -249
  19. package/lib/heat.js +142 -136
  20. package/lib/hot-memory.js +46 -46
  21. package/lib/index.js +515 -515
  22. package/lib/inject.js +299 -295
  23. package/lib/lang.js +202 -179
  24. package/lib/local-embedder.js +320 -320
  25. package/lib/mirror.js +198 -198
  26. package/lib/quality-filter.js +126 -126
  27. package/lib/recall-stats.js +103 -0
  28. package/lib/reranker.js +269 -269
  29. package/lib/runtime/adopt.js +176 -176
  30. package/lib/runtime/closure.js +172 -172
  31. package/lib/runtime/download.js +247 -247
  32. package/lib/runtime/layout.js +235 -235
  33. package/lib/runtime/loader.js +249 -249
  34. package/lib/runtime/model-fetch.js +361 -361
  35. package/lib/runtime/provision.js +237 -237
  36. package/lib/runtime/tarball.js +130 -130
  37. package/lib/runtime/verify.js +191 -191
  38. package/lib/scope.js +118 -118
  39. package/lib/search/adaptive.js +22 -22
  40. package/lib/search/bm25.js +96 -96
  41. package/lib/service.js +2171 -2087
  42. package/lib/settings.js +430 -420
  43. package/lib/store.js +2448 -2367
  44. package/lib/summarize.js +575 -449
  45. package/lib/tools.js +574 -574
  46. package/lib/vector-index.js +110 -110
  47. package/lib/version-check.js +122 -122
  48. package/package.json +109 -108
  49. package/runtime-manifest.json +596 -596
  50. package/scripts/benchmark-embed.js +201 -201
  51. package/scripts/benchmark-recall.js +199 -199
  52. package/scripts/benchmark-rerank.js +166 -166
  53. package/scripts/build-runtime-manifest.mjs +217 -217
  54. package/scripts/check-sync.js +42 -42
  55. package/scripts/e2e-dsh.js +220 -220
  56. package/scripts/mneme-runtime.mjs +277 -277
  57. package/scripts/stress-dsh.js +255 -255
  58. package/scripts/sync-lib.js +47 -47
  59. package/scripts/sync-test-badge.mjs +61 -61
  60. package/src/api-standalone.js +495 -316
  61. package/src/api.js +1382 -1316
  62. package/src/bootstrap.js +211 -0
  63. package/src/commands.js +95 -95
  64. package/src/config.js +533 -510
  65. package/src/dream/clustering.js +118 -118
  66. package/src/dream/decisions.js +658 -658
  67. package/src/dream/narratives.js +44 -0
  68. package/src/dream/sleep.js +700 -700
  69. package/src/dream.js +1319 -1216
  70. package/src/embedding.js +177 -177
  71. package/src/entities/extractor.js +249 -249
  72. package/src/heat.js +142 -136
  73. package/src/hot-memory.js +46 -46
  74. package/src/index.js +515 -515
  75. package/src/inject.js +299 -295
  76. package/src/lang.js +202 -179
  77. package/src/local-embedder.js +320 -320
  78. package/src/mirror.js +198 -198
  79. package/src/quality-filter.js +126 -126
  80. package/src/recall-stats.js +103 -0
  81. package/src/reranker.js +269 -269
  82. package/src/runtime/adopt.js +176 -176
  83. package/src/runtime/closure.js +172 -172
  84. package/src/runtime/download.js +247 -247
  85. package/src/runtime/layout.js +235 -235
  86. package/src/runtime/loader.js +249 -249
  87. package/src/runtime/model-fetch.js +361 -361
  88. package/src/runtime/provision.js +237 -237
  89. package/src/runtime/tarball.js +130 -130
  90. package/src/runtime/verify.js +191 -191
  91. package/src/scope.js +118 -118
  92. package/src/search/adaptive.js +22 -22
  93. package/src/search/bm25.js +96 -96
  94. package/src/service.js +2171 -2087
  95. package/src/settings.js +430 -420
  96. package/src/store.js +2448 -2367
  97. package/src/summarize.js +575 -449
  98. package/src/tools.js +574 -574
  99. package/src/vector-index.js +110 -110
  100. package/src/version-check.js +122 -122
  101. package/test/api-routes-gaps.test.js +218 -218
  102. package/test/api.test.js +1578 -1482
  103. package/test/audit.test.js +448 -448
  104. package/test/benchmark.test.js +94 -94
  105. package/test/bootstrap.test.js +220 -0
  106. package/test/client.test.js +799 -736
  107. package/test/clustering.test.js +100 -100
  108. package/test/commands.test.js +106 -106
  109. package/test/config.test.js +66 -66
  110. package/test/conflict-freeze.test.js +300 -300
  111. package/test/dream-archive-guardrail.test.js +116 -116
  112. package/test/dream-candidate-hybrid.test.js +281 -281
  113. package/test/dream-coverage-degrade.test.js +86 -86
  114. package/test/dream.test.js +1257 -1254
  115. package/test/embedding-ready.test.js +196 -196
  116. package/test/entities.test.js +547 -547
  117. package/test/entity-recall.test.js +179 -0
  118. package/test/epistemic.test.js +298 -298
  119. package/test/fnew-0112.test.js +311 -311
  120. package/test/fnew-03.test.js +422 -422
  121. package/test/graph-api.test.js +175 -175
  122. package/test/heat.test.js +175 -148
  123. package/test/helpers/dream-mock.js +82 -82
  124. package/test/helpers/peer-worker.mjs +25 -25
  125. package/test/helpers/runtime-source.js +60 -60
  126. package/test/helpers/tar-builder.js +80 -80
  127. package/test/hot-memory.test.js +145 -145
  128. package/test/inject-content-cap.test.js +89 -0
  129. package/test/inject-first-round-bm25.test.js +89 -89
  130. package/test/inject-heat.test.js +61 -0
  131. package/test/inject-rotation.test.js +161 -161
  132. package/test/inject.test.js +249 -249
  133. package/test/lang.test.js +87 -87
  134. package/test/lib-smoke.test.js +96 -96
  135. package/test/llm-audit.test.js +309 -309
  136. package/test/llm-message-source.test.js +177 -177
  137. package/test/local-embedder.test.js +249 -249
  138. package/test/mcp-stdio.test.js +385 -0
  139. package/test/mirror-dirty.test.js +424 -424
  140. package/test/mirror-edit-digest.test.js +187 -187
  141. package/test/mirror-generation.test.js +499 -499
  142. package/test/mirror.test.js +249 -249
  143. package/test/narrative-bars.test.js +162 -0
  144. package/test/peer-blockers.test.js +193 -193
  145. package/test/policy-epoch.test.js +259 -259
  146. package/test/quality-filter.test.js +186 -186
  147. package/test/reasoning-effort.test.js +746 -746
  148. package/test/recall-evals.test.js +235 -235
  149. package/test/recall-layer.test.js +326 -326
  150. package/test/recall-stats.test.js +117 -0
  151. package/test/receipt-chain.test.js +451 -451
  152. package/test/reflection.test.js +226 -226
  153. package/test/reindex-backfill.test.js +62 -62
  154. package/test/reranker-single-logit.test.js +73 -73
  155. package/test/reranker.test.js +197 -197
  156. package/test/resident-status.test.js +83 -0
  157. package/test/runtime-adopt.test.js +206 -206
  158. package/test/runtime-cli.test.js +89 -89
  159. package/test/runtime-closure.test.js +193 -193
  160. package/test/runtime-download.test.js +302 -302
  161. package/test/runtime-layout.test.js +163 -163
  162. package/test/runtime-loader.test.js +237 -237
  163. package/test/runtime-manifest.test.js +158 -158
  164. package/test/runtime-model-fetch.test.js +348 -348
  165. package/test/runtime-provision.test.js +101 -101
  166. package/test/runtime-tarball.test.js +81 -81
  167. package/test/runtime-verify.test.js +214 -214
  168. package/test/scope-candidates.test.js +239 -239
  169. package/test/scope-explicit.test.js +452 -452
  170. package/test/scope-retrieval.test.js +197 -197
  171. package/test/scope-storage.test.js +255 -255
  172. package/test/scope-strict.test.js +231 -231
  173. package/test/search-fusion.test.js +90 -90
  174. package/test/semantic.test.js +124 -124
  175. package/test/service-search.test.js +174 -174
  176. package/test/service.test.js +405 -405
  177. package/test/settings.test.js +261 -261
  178. package/test/skip-invalid-restore.test.js +262 -262
  179. package/test/sleep-action-set.test.js +422 -422
  180. package/test/sleep-heat.test.js +126 -125
  181. package/test/sleep-scheduler-rearm.test.js +89 -89
  182. package/test/sleep.test.js +373 -373
  183. package/test/standalone-api.test.js +544 -359
  184. package/test/store-vector-cache.test.js +98 -98
  185. package/test/store.test.js +383 -383
  186. package/test/stress.test.js +209 -209
  187. package/test/summarize.test.js +884 -575
  188. package/test/tools-memory-get-schema.test.js +65 -65
  189. package/test/tools.test.js +341 -341
  190. package/test/updated-at-semantics.test.js +113 -113
  191. package/test/vector-index.test.js +221 -221
  192. package/test/version-check.test.js +152 -152
  193. package/test/webServer-optional.test.js +82 -82
@@ -1,316 +1,495 @@
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
+ // 内容被改写时旧版本先入档(human_override),与内部面板写路径一致。
170
+ if (patch.content !== undefined && patch.content !== existing.content) {
171
+ const history = Array.isArray(existing.content_history) ? existing.content_history : [];
172
+ patch.content_history = [
173
+ { content: existing.content ?? "", source: "human_override", updated_at: new Date().toISOString() },
174
+ ...history
175
+ ].slice(0, 20);
176
+ }
177
+ service.update(id, patch, {
178
+ actor: "tool",
179
+ ...(typeof body.reason === "string" && body.reason.trim() ? { query: body.reason.trim() } : {})
180
+ });
181
+ sendJson(res, 200, { memory: service.toApiList([service.getById(id)])[0] });
182
+ }
183
+
184
+ /**
185
+ * Create (and start) the standalone API server.
186
+ * Accepts { service, store, config, logger, settings, port, host }:
187
+ * - token: persisted settings kv "external_api" wins; auto-generated
188
+ * (crypto.randomBytes(24).toString("base64url")) and persisted when empty.
189
+ * - port: explicit arg > persisted settings > config.externalApiPort > 8790.
190
+ * - host: explicit arg > config.externalApiHost > "127.0.0.1".
191
+ * Returns { server, port, host, token, ready }: `port` is the effective bound
192
+ * port (updated to the OS-assigned one after `ready` resolves when asked to
193
+ * bind port 0), `ready` resolves once listening and rejects if the bind fails.
194
+ */
195
+ export function createStandaloneApi({ service, store, config = {}, logger, settings, port, host }) {
196
+ const persisted = settings?.getExternalApi?.() ?? {};
197
+
198
+ let token = typeof persisted.token === "string" ? persisted.token : "";
199
+ if (!token) {
200
+ token = randomBytes(24).toString("base64url");
201
+ // Persist only the token; enabled/port keys stay as they are (merge).
202
+ try {
203
+ settings?.setExternalApi?.({ token });
204
+ } catch (error) {
205
+ logger?.warn?.(`[dsh-mneme] standalone API token persistence failed: ${String(error)}`);
206
+ }
207
+ }
208
+
209
+ // Persisted host (set from the panel) wins over the bundle config, same
210
+ // precedence as port; the explicit argument still wins over both.
211
+ const boundHost = host
212
+ ?? (typeof persisted.host === "string" && persisted.host ? persisted.host : undefined)
213
+ ?? config.externalApiHost
214
+ ?? DEFAULT_HOST;
215
+ const persistedPort = Number(persisted.port);
216
+ const boundPort = port
217
+ ?? (Number.isInteger(persistedPort) && persistedPort > 0 ? persistedPort : undefined)
218
+ ?? config.externalApiPort
219
+ ?? DEFAULT_PORT;
220
+
221
+ const server = createServer((req, res) => {
222
+ try {
223
+ const url = new URL(req.url ?? "/", "http://localhost");
224
+ const pathname = url.pathname;
225
+
226
+ // Health is the single unauthenticated probe (monitor checks).
227
+ if (req.method === "GET" && pathname === "/health") {
228
+ sendJson(res, 200, { ok: true });
229
+ return;
230
+ }
231
+
232
+ // Everything else requires the Bearer token.
233
+ if (!isAuthorized(req, token)) {
234
+ sendJson(res, 401, { error: "unauthorized" });
235
+ return;
236
+ }
237
+
238
+ // --- GET /status: version + store shape + uptime -----------------------
239
+ if (req.method === "GET" && pathname === "/status") {
240
+ const byType = {};
241
+ for (const type of TYPES) byType[type] = service.count(type);
242
+ let entities = 0;
243
+ try {
244
+ entities = store.db.prepare("SELECT count(*) AS c FROM entities").get().c;
245
+ } catch { /* entities storage unavailable → 0 */ }
246
+ sendJson(res, 200, {
247
+ version: VERSION,
248
+ memories: { total: service.count(), byType },
249
+ entities,
250
+ uptime_s: Math.floor(process.uptime())
251
+ });
252
+ return;
253
+ }
254
+
255
+ // --- GET /profile: user self-description -------------------------------
256
+ if (req.method === "GET" && pathname === "/profile") {
257
+ sendJson(res, 200, { profile: settings?.getProfile?.() ?? "" });
258
+ return;
259
+ }
260
+
261
+ // --- GET /rules: agent behavior rules -----------------------------------
262
+ if (req.method === "GET" && pathname === "/rules") {
263
+ sendJson(res, 200, { rules: settings?.getRules?.() ?? [] });
264
+ return;
265
+ }
266
+
267
+ // --- GET /memories: paged + filtered list (same semantics as the
268
+ // internal /api/dsh-mneme/list) ------------------------------------
269
+ if (req.method === "GET" && pathname === "/memories") {
270
+ const type = url.searchParams.get("type") ?? undefined;
271
+ const limit = Number(url.searchParams.get("limit") ?? 50);
272
+ const offset = Number(url.searchParams.get("offset") ?? 0);
273
+ const order = url.searchParams.get("order") ?? undefined;
274
+ const minRaw = url.searchParams.get("minImportance");
275
+ const minImportance = minRaw !== null && minRaw !== "" && !Number.isNaN(Number(minRaw))
276
+ ? Number(minRaw)
277
+ : undefined;
278
+ const source = url.searchParams.get("source") || undefined;
279
+ // include_archived + occurred 时间窗:与 memory_list 工具同口径(工具
280
+ // 面六件套经 8790 全量可用,#181);缺省行为与既有调用方逐字节一致。
281
+ const includeArchived = url.searchParams.get("include_archived") === "true";
282
+ const occurredFrom = url.searchParams.get("occurred_from") ?? undefined;
283
+ const occurredTo = url.searchParams.get("occurred_to") ?? undefined;
284
+ const listFilters = { includeArchived, ...(occurredFrom ? { occurredFrom } : {}), ...(occurredTo ? { occurredTo } : {}) };
285
+ const items = service.toApiList(service.list({ type, limit, offset, order, minImportance, source, ...listFilters }));
286
+ // Total honors the same filters so pager math stays correct.
287
+ sendJson(res, 200, { items, total: service.count(type, { minImportance, source, ...listFilters }) });
288
+ return;
289
+ }
290
+
291
+ // --- GET/PUT/DELETE /memories/:id --------------------------------------
292
+ const idMatch = pathname.match(/^\/memories\/([^/]+)$/);
293
+ if (idMatch) {
294
+ let id = idMatch[1];
295
+ try { id = decodeURIComponent(id); } catch { /* keep raw */ }
296
+ if (req.method === "GET") {
297
+ const row = service.getById(id);
298
+ if (!row) {
299
+ sendJson(res, 404, { error: "not-found" });
300
+ return;
301
+ }
302
+ sendJson(res, 200, service.toApiList([row])[0]);
303
+ return;
304
+ }
305
+ if (req.method === "DELETE") {
306
+ // store.remove deletes silently — precheck for a distinguishable 404.
307
+ if (!service.getById(id)) {
308
+ sendJson(res, 404, { error: "not-found" });
309
+ return;
310
+ }
311
+ service.remove(id);
312
+ sendJson(res, 200, { ok: true });
313
+ return;
314
+ }
315
+ // --- PUT: field patch(memory_update 工具的外部通道,#181)。字段校验
316
+ // 与内部 /api/dsh-mneme/update 同风格:字段出现就必须合法,宁 400 不静默
317
+ // 纠正;content 改写按 human_override 入档;scope 修正归一化在 service
318
+ // 层做(null=放宽到全局,字符串=收窄/改标),审计 actor 记 "tool"。
319
+ // 整个异步回调套 try/catch:service 抛错不能变成未处理拒绝(Node 默认
320
+ // 策略下会终止宿主进程)或悬着不回的请求(外层同步 try 捕不到这里)。
321
+ if (req.method === "PUT") {
322
+ void readBody(req).then(async (text) => {
323
+ try {
324
+ await handlePutBody(res, service, logger, id, text);
325
+ } catch (error) {
326
+ logger?.warn?.(`[dsh-mneme] standalone API update failed: ${String(error)}`);
327
+ sendJson(res, 500, { error: "internal" });
328
+ }
329
+ });
330
+ return;
331
+ }
332
+ sendJson(res, 404, { error: "not-found" });
333
+ return;
334
+ }
335
+
336
+ // --- POST /memories: save with title-dedupe (safer than raw save) ------
337
+ if (req.method === "POST" && pathname === "/memories") {
338
+ void readBody(req).then((text) => {
339
+ let body;
340
+ try {
341
+ body = JSON.parse(text || "{}");
342
+ } catch {
343
+ sendJson(res, 400, { error: "invalid-json" });
344
+ return;
345
+ }
346
+ if (body === null || typeof body !== "object" || Array.isArray(body)) {
347
+ sendJson(res, 400, { error: "invalid-body" });
348
+ return;
349
+ }
350
+ // Pre-validate what store.save would throw on, so clients get a
351
+ // clean 400 instead of a leaked SQLite error.
352
+ if (!TYPES.has(body.type)) {
353
+ sendJson(res, 400, { error: "invalid-type" });
354
+ return;
355
+ }
356
+ if (typeof body.title !== "string" || !body.title.trim()) {
357
+ sendJson(res, 400, { error: "missing-title" });
358
+ return;
359
+ }
360
+ if (typeof body.content !== "string") {
361
+ sendJson(res, 400, { error: "missing-content" });
362
+ return;
363
+ }
364
+ if (body.tags !== undefined && !Array.isArray(body.tags)) {
365
+ sendJson(res, 400, { error: "tags-must-be-an-array" });
366
+ return;
367
+ }
368
+ // memory_save 工具的其余可选字段(#181):sensitivity / occurred_at /
369
+ // 显式 scope。scope 仅收显式声明(standalone API 无会话上下文,自动
370
+ // 标注无从解析,语义与工具的显式参数一致);形状不对宁 400 不静默丢。
371
+ for (const key of ["sensitivity", "occurred_at", "agent_scope", "workspace_scope"]) {
372
+ if (body[key] !== undefined && (typeof body[key] !== "string" || !body[key].trim())) {
373
+ sendJson(res, 400, { error: `invalid-${key.replace(/_/g, "-")}` });
374
+ return;
375
+ }
376
+ }
377
+ try {
378
+ const { action, memory } = service.saveWithDedupe({
379
+ type: body.type,
380
+ title: body.title,
381
+ content: body.content,
382
+ importance: body.importance,
383
+ tags: body.tags,
384
+ source: body.source,
385
+ ...(body.sensitivity !== undefined ? { sensitivity: body.sensitivity } : {}),
386
+ ...(body.occurred_at !== undefined ? { occurred_at: body.occurred_at } : {}),
387
+ ...(body.agent_scope !== undefined ? { agent_scope: body.agent_scope, agent_scope_source: "explicit" } : {}),
388
+ ...(body.workspace_scope !== undefined ? { workspace_scope: body.workspace_scope, workspace_scope_source: "explicit" } : {})
389
+ });
390
+ // action 随行透出(created/merged):memory_save 工具语义对齐所需,
391
+ // 附加键对既有消费方(CLI add 等)向后兼容。
392
+ sendJson(res, action === "created" ? 201 : 200, { ...service.toApiList([memory])[0], action });
393
+ } catch (error) {
394
+ logger?.warn?.(`[dsh-mneme] standalone API save failed: ${String(error)}`);
395
+ sendJson(res, 500, { error: "internal" });
396
+ }
397
+ });
398
+ return;
399
+ }
400
+
401
+ // --- POST /bootstrap: cold-start memories from repo files (#220) -------
402
+ // 显式收 dir(插件没有工作区根目录概念,不猜路径);确定性解析零 LLM;
403
+ // 幂等骑 saveWithDedupe 的 (type, title, scope) 去重 + _overwrite 刷新。
404
+ if (req.method === "POST" && pathname === "/bootstrap") {
405
+ void readBody(req).then((text) => {
406
+ let body;
407
+ try {
408
+ body = JSON.parse(text || "{}");
409
+ } catch {
410
+ sendJson(res, 400, { error: "invalid-json" });
411
+ return;
412
+ }
413
+ if (body === null || typeof body !== "object" || Array.isArray(body)) {
414
+ sendJson(res, 400, { error: "invalid-body" });
415
+ return;
416
+ }
417
+ if (typeof body.dir !== "string" || !body.dir.trim()) {
418
+ sendJson(res, 400, { error: "missing-dir" });
419
+ return;
420
+ }
421
+ bootstrapFromDirectory({ service, dir: body.dir, logger })
422
+ .then((summary) => sendJson(res, 200, summary))
423
+ .catch((error) => {
424
+ if (error?.code) {
425
+ sendJson(res, 400, { error: error.code });
426
+ return;
427
+ }
428
+ logger?.warn?.(`[dsh-mneme] standalone API bootstrap failed: ${String(error)}`);
429
+ sendJson(res, 500, { error: "internal" });
430
+ });
431
+ });
432
+ return;
433
+ }
434
+
435
+ // --- GET /search: unified recall pipeline (keyword + vector + BM25) ----
436
+ if (req.method === "GET" && pathname === "/search") {
437
+ const q = url.searchParams.get("q") ?? "";
438
+ const limit = Number(url.searchParams.get("topK") ?? url.searchParams.get("limit") ?? 20);
439
+ const mode = url.searchParams.get("mode") ?? "auto";
440
+ const rerank = url.searchParams.get("rerank") !== "false";
441
+ const occurredFrom = url.searchParams.get("occurred_from") ?? null;
442
+ const occurredTo = url.searchParams.get("occurred_to") ?? null;
443
+ const query = q.trim();
444
+ if (!query) {
445
+ sendJson(res, 200, { items: [], mode: "keyword" });
446
+ return;
447
+ }
448
+ // Any vector/rerank failure degrades to keyword inside searchMemories.
449
+ void Promise.resolve(
450
+ service.searchMemories(query, {
451
+ mode,
452
+ topK: limit,
453
+ useRerank: rerank,
454
+ ...(occurredFrom !== null || occurredTo !== null ? { occurredFrom, occurredTo } : {})
455
+ })
456
+ ).then((rows) => {
457
+ const used = rows.some((m) => m.vector === true) ? "vector" : "keyword";
458
+ sendJson(res, 200, { items: service.toApiList(rows), mode: used });
459
+ }).catch(() => {
460
+ sendJson(res, 200, { items: service.toApiList(service.search(query, { limit })), mode: "keyword" });
461
+ });
462
+ return;
463
+ }
464
+
465
+ sendJson(res, 404, { error: "not-found" });
466
+ } catch {
467
+ sendJson(res, 500, { error: "internal" });
468
+ }
469
+ });
470
+
471
+ // A permanent error listener keeps an EADDRINUSE / runtime socket error from
472
+ // crashing the host process; `ready` still surfaces the first bind failure.
473
+ server.on("error", (error) => {
474
+ logger?.warn?.(`[dsh-mneme] standalone API error: ${String(error)}`);
475
+ });
476
+ const ready = new Promise((resolve, reject) => {
477
+ // listening handled by listenWithRetry
478
+ listenWithRetry(server, boundPort, boundHost, logger).then(resolve, reject);
479
+ });
480
+ // server.listen is called inside listenWithRetry
481
+ ready.then(() => {
482
+ const address = server.address();
483
+ if (address && typeof address === "object") {
484
+ logger?.info?.(`[dsh-mneme] standalone API listening on http://${address.address}:${address.port}`);
485
+ }
486
+ }).catch(() => { /* already logged by the error handler above */ });
487
+
488
+ const api = { server, port: boundPort, host: boundHost, token, ready };
489
+ // After the OS assigns the real port (bind port 0), reflect it for callers.
490
+ ready.then(() => {
491
+ const address = server.address();
492
+ if (address && typeof address === "object") api.port = address.port;
493
+ }).catch(() => { /* bind failed: port stays as configured */ });
494
+ return api;
495
+ }