@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.
- package/LICENSE +21 -21
- package/README.md +718 -636
- package/bin/cli.mjs +0 -0
- package/bin/dsh-mneme-mcp.mjs +502 -0
- package/cordis.patch.yml +21 -21
- package/lib/api-standalone.js +495 -316
- package/lib/api.js +1382 -1316
- package/lib/bootstrap.js +211 -0
- package/lib/client.js +4475 -4366
- package/lib/commands.js +95 -95
- package/lib/config.js +533 -510
- package/lib/dream/clustering.js +118 -118
- package/lib/dream/decisions.js +658 -658
- package/lib/dream/narratives.js +44 -0
- package/lib/dream/sleep.js +700 -700
- package/lib/dream.js +1319 -1216
- package/lib/embedding.js +177 -177
- package/lib/entities/extractor.js +249 -249
- package/lib/heat.js +142 -136
- package/lib/hot-memory.js +46 -46
- package/lib/index.js +515 -515
- package/lib/inject.js +299 -295
- package/lib/lang.js +202 -179
- package/lib/local-embedder.js +320 -320
- package/lib/mirror.js +198 -198
- package/lib/quality-filter.js +126 -126
- package/lib/recall-stats.js +103 -0
- package/lib/reranker.js +269 -269
- package/lib/runtime/adopt.js +176 -176
- package/lib/runtime/closure.js +172 -172
- package/lib/runtime/download.js +247 -247
- package/lib/runtime/layout.js +235 -235
- package/lib/runtime/loader.js +249 -249
- package/lib/runtime/model-fetch.js +361 -361
- package/lib/runtime/provision.js +237 -237
- package/lib/runtime/tarball.js +130 -130
- package/lib/runtime/verify.js +191 -191
- package/lib/scope.js +118 -118
- package/lib/search/adaptive.js +22 -22
- package/lib/search/bm25.js +96 -96
- package/lib/service.js +2171 -2087
- package/lib/settings.js +430 -420
- package/lib/store.js +2448 -2367
- package/lib/summarize.js +575 -449
- package/lib/tools.js +574 -574
- package/lib/vector-index.js +110 -110
- package/lib/version-check.js +122 -122
- package/package.json +109 -108
- package/runtime-manifest.json +596 -596
- package/scripts/benchmark-embed.js +201 -201
- package/scripts/benchmark-recall.js +199 -199
- package/scripts/benchmark-rerank.js +166 -166
- package/scripts/build-runtime-manifest.mjs +217 -217
- package/scripts/check-sync.js +42 -42
- package/scripts/e2e-dsh.js +220 -220
- package/scripts/mneme-runtime.mjs +277 -277
- package/scripts/stress-dsh.js +255 -255
- package/scripts/sync-lib.js +47 -47
- package/scripts/sync-test-badge.mjs +61 -61
- package/src/api-standalone.js +495 -316
- package/src/api.js +1382 -1316
- package/src/bootstrap.js +211 -0
- package/src/commands.js +95 -95
- package/src/config.js +533 -510
- package/src/dream/clustering.js +118 -118
- package/src/dream/decisions.js +658 -658
- package/src/dream/narratives.js +44 -0
- package/src/dream/sleep.js +700 -700
- package/src/dream.js +1319 -1216
- package/src/embedding.js +177 -177
- package/src/entities/extractor.js +249 -249
- package/src/heat.js +142 -136
- package/src/hot-memory.js +46 -46
- package/src/index.js +515 -515
- package/src/inject.js +299 -295
- package/src/lang.js +202 -179
- package/src/local-embedder.js +320 -320
- package/src/mirror.js +198 -198
- package/src/quality-filter.js +126 -126
- package/src/recall-stats.js +103 -0
- package/src/reranker.js +269 -269
- package/src/runtime/adopt.js +176 -176
- package/src/runtime/closure.js +172 -172
- package/src/runtime/download.js +247 -247
- package/src/runtime/layout.js +235 -235
- package/src/runtime/loader.js +249 -249
- package/src/runtime/model-fetch.js +361 -361
- package/src/runtime/provision.js +237 -237
- package/src/runtime/tarball.js +130 -130
- package/src/runtime/verify.js +191 -191
- package/src/scope.js +118 -118
- package/src/search/adaptive.js +22 -22
- package/src/search/bm25.js +96 -96
- package/src/service.js +2171 -2087
- package/src/settings.js +430 -420
- package/src/store.js +2448 -2367
- package/src/summarize.js +575 -449
- package/src/tools.js +574 -574
- package/src/vector-index.js +110 -110
- package/src/version-check.js +122 -122
- package/test/api-routes-gaps.test.js +218 -218
- package/test/api.test.js +1578 -1482
- package/test/audit.test.js +448 -448
- package/test/benchmark.test.js +94 -94
- package/test/bootstrap.test.js +220 -0
- package/test/client.test.js +799 -736
- package/test/clustering.test.js +100 -100
- package/test/commands.test.js +106 -106
- package/test/config.test.js +66 -66
- package/test/conflict-freeze.test.js +300 -300
- package/test/dream-archive-guardrail.test.js +116 -116
- package/test/dream-candidate-hybrid.test.js +281 -281
- package/test/dream-coverage-degrade.test.js +86 -86
- package/test/dream.test.js +1257 -1254
- package/test/embedding-ready.test.js +196 -196
- package/test/entities.test.js +547 -547
- package/test/entity-recall.test.js +179 -0
- package/test/epistemic.test.js +298 -298
- package/test/fnew-0112.test.js +311 -311
- package/test/fnew-03.test.js +422 -422
- package/test/graph-api.test.js +175 -175
- package/test/heat.test.js +175 -148
- package/test/helpers/dream-mock.js +82 -82
- package/test/helpers/peer-worker.mjs +25 -25
- package/test/helpers/runtime-source.js +60 -60
- package/test/helpers/tar-builder.js +80 -80
- package/test/hot-memory.test.js +145 -145
- package/test/inject-content-cap.test.js +89 -0
- package/test/inject-first-round-bm25.test.js +89 -89
- package/test/inject-heat.test.js +61 -0
- package/test/inject-rotation.test.js +161 -161
- package/test/inject.test.js +249 -249
- package/test/lang.test.js +87 -87
- package/test/lib-smoke.test.js +96 -96
- package/test/llm-audit.test.js +309 -309
- package/test/llm-message-source.test.js +177 -177
- package/test/local-embedder.test.js +249 -249
- package/test/mcp-stdio.test.js +385 -0
- package/test/mirror-dirty.test.js +424 -424
- package/test/mirror-edit-digest.test.js +187 -187
- package/test/mirror-generation.test.js +499 -499
- package/test/mirror.test.js +249 -249
- package/test/narrative-bars.test.js +162 -0
- package/test/peer-blockers.test.js +193 -193
- package/test/policy-epoch.test.js +259 -259
- package/test/quality-filter.test.js +186 -186
- package/test/reasoning-effort.test.js +746 -746
- package/test/recall-evals.test.js +235 -235
- package/test/recall-layer.test.js +326 -326
- package/test/recall-stats.test.js +117 -0
- package/test/receipt-chain.test.js +451 -451
- package/test/reflection.test.js +226 -226
- package/test/reindex-backfill.test.js +62 -62
- package/test/reranker-single-logit.test.js +73 -73
- package/test/reranker.test.js +197 -197
- package/test/resident-status.test.js +83 -0
- package/test/runtime-adopt.test.js +206 -206
- package/test/runtime-cli.test.js +89 -89
- package/test/runtime-closure.test.js +193 -193
- package/test/runtime-download.test.js +302 -302
- package/test/runtime-layout.test.js +163 -163
- package/test/runtime-loader.test.js +237 -237
- package/test/runtime-manifest.test.js +158 -158
- package/test/runtime-model-fetch.test.js +348 -348
- package/test/runtime-provision.test.js +101 -101
- package/test/runtime-tarball.test.js +81 -81
- package/test/runtime-verify.test.js +214 -214
- package/test/scope-candidates.test.js +239 -239
- package/test/scope-explicit.test.js +452 -452
- package/test/scope-retrieval.test.js +197 -197
- package/test/scope-storage.test.js +255 -255
- package/test/scope-strict.test.js +231 -231
- package/test/search-fusion.test.js +90 -90
- package/test/semantic.test.js +124 -124
- package/test/service-search.test.js +174 -174
- package/test/service.test.js +405 -405
- package/test/settings.test.js +261 -261
- package/test/skip-invalid-restore.test.js +262 -262
- package/test/sleep-action-set.test.js +422 -422
- package/test/sleep-heat.test.js +126 -125
- package/test/sleep-scheduler-rearm.test.js +89 -89
- package/test/sleep.test.js +373 -373
- package/test/standalone-api.test.js +544 -359
- package/test/store-vector-cache.test.js +98 -98
- package/test/store.test.js +383 -383
- package/test/stress.test.js +209 -209
- package/test/summarize.test.js +884 -575
- package/test/tools-memory-get-schema.test.js +65 -65
- package/test/tools.test.js +341 -341
- package/test/updated-at-semantics.test.js +113 -113
- package/test/vector-index.test.js +221 -221
- package/test/version-check.test.js +152 -152
- package/test/webServer-optional.test.js +82 -82
package/src/api-standalone.js
CHANGED
|
@@ -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
|
-
//
|
|
8
|
-
//
|
|
9
|
-
//
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
if (error?.code === "EADDRINUSE") {
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
*
|
|
93
|
-
*
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
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
|
+
}
|