@modusensus/dsh-mneme 0.1.6 → 0.2.1

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/lib/api.js CHANGED
@@ -1,245 +1,256 @@
1
- import { URL } from "node:url";
2
-
3
- function sendJson(res, status, payload) {
4
- res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
5
- res.end(JSON.stringify(payload));
6
- }
7
-
8
- /** Collect the request body as text (tolerant of empty/invalid bodies). */
9
- function readBody(req) {
10
- return new Promise((resolve) => {
11
- let body = "";
12
- req.on("data", (chunk) => { body += chunk; });
13
- req.on("end", () => resolve(body));
14
- req.on("error", () => resolve(""));
15
- });
16
- }
17
-
18
- function parseBody(text) {
19
- try {
20
- return JSON.parse(text || "{}");
21
- } catch {
22
- return {};
23
- }
24
- }
25
-
26
- export function createApi(ctx, service, settings, commands, embedder) {
27
- const disposers = [];
28
-
29
- const register = (route) => {
30
- disposers.push(ctx.webServer.register(route));
31
- };
32
-
33
- // /api/dsh-mneme prefix fallback → 404 JSON for unknown sub-paths
34
- register({
35
- kind: "prefix",
36
- path: "/api/dsh-mneme",
37
- handler(req, res) {
38
- sendJson(res, 404, { error: "not-found" });
39
- }
40
- });
41
-
42
- register({
43
- kind: "exact",
44
- path: "/api/dsh-mneme/list",
45
- handler(req, res) {
46
- try {
47
- const url = new URL(req.url, "http://localhost");
48
- const type = url.searchParams.get("type") ?? undefined;
49
- const limit = Number(url.searchParams.get("limit") ?? 50);
50
- const offset = Number(url.searchParams.get("offset") ?? 0);
51
- const items = service.toApiList(service.list({ type, limit, offset }));
52
- sendJson(res, 200, { items, total: service.count(type) });
53
- } catch {
54
- sendJson(res, 500, { error: "internal" });
55
- }
56
- }
57
- });
58
-
59
- register({
60
- kind: "exact",
61
- path: "/api/dsh-mneme/search",
62
- handler(req, res) {
63
- try {
64
- const url = new URL(req.url, "http://localhost");
65
- const q = url.searchParams.get("q") ?? "";
66
- const limit = Number(url.searchParams.get("limit") ?? 20);
67
- // mode: auto (default) | keyword | vector
68
- const mode = url.searchParams.get("mode") ?? "auto";
69
- const query = q.trim();
70
- if (!query) {
71
- sendJson(res, 200, { items: [], mode: "keyword" });
72
- return;
73
- }
74
- // Keyword results (existing behavior) always computed; used as a
75
- // fallback and as the primary ranking when vector is unavailable.
76
- const keyword = service.toApiList(service.search(query, { limit }));
77
- if (mode === "keyword" || !embedder) {
78
- sendJson(res, 200, { items: keyword, mode: "keyword" });
79
- return;
80
- }
81
- const cfg = settings.getVectorConfig();
82
- if (mode === "vector" && !cfg?.enabled) {
83
- sendJson(res, 200, { items: keyword, mode: "keyword", error: "vector-disabled" });
84
- return;
85
- }
86
- // Try vector search; on any failure fall back to keyword results.
87
- return embedder.embed(query).then(async (vector) => {
88
- let items = keyword;
89
- let used = "keyword";
90
- if (vector) {
91
- const scored = service.toApiList(service.searchVector(vector, { limit }));
92
- // Merge: keyword exact hits first (they are the user's literal
93
- // words), then vector results fill the remaining slots, deduped.
94
- const seen = new Set(keyword.map((m) => m.id));
95
- const merged = [...keyword];
96
- for (const m of scored) {
97
- if (merged.length >= limit) break;
98
- if (!seen.has(m.id)) {
99
- seen.add(m.id);
100
- merged.push(m);
101
- }
102
- }
103
- items = merged;
104
- used = "vector";
105
- }
106
- sendJson(res, 200, { items, mode: used });
107
- }).catch(() => {
108
- sendJson(res, 200, { items: keyword, mode: "keyword" });
109
- });
110
- } catch {
111
- sendJson(res, 500, { error: "internal" });
112
- }
113
- }
114
- });
115
-
116
- // --- user profile ---
117
- register({
118
- kind: "exact",
119
- path: "/api/dsh-mneme/profile",
120
- handler(req, res) {
121
- try {
122
- if (req.method === "PUT" || req.method === "POST") {
123
- return readBody(req).then((text) => {
124
- const body = parseBody(text);
125
- settings.setProfile(typeof body.profile === "string" ? body.profile : "");
126
- sendJson(res, 200, { profile: settings.getProfile() });
127
- });
128
- }
129
- sendJson(res, 200, { profile: settings.getProfile() });
130
- } catch {
131
- sendJson(res, 500, { error: "internal" });
132
- }
133
- }
134
- });
135
-
136
- // --- rules ---
137
- register({
138
- kind: "exact",
139
- path: "/api/dsh-mneme/rules",
140
- handler(req, res) {
141
- try {
142
- if (req.method === "PUT" || req.method === "POST") {
143
- return readBody(req).then((text) => {
144
- const body = parseBody(text);
145
- settings.setRules(Array.isArray(body.rules) ? body.rules : []);
146
- sendJson(res, 200, { rules: settings.getRules() });
147
- });
148
- }
149
- sendJson(res, 200, { rules: settings.getRules() });
150
- } catch {
151
- sendJson(res, 500, { error: "internal" });
152
- }
153
- }
154
- });
155
-
156
- // --- vector search config ---
157
- register({
158
- kind: "exact",
159
- path: "/api/dsh-mneme/vector-config",
160
- handler(req, res) {
161
- try {
162
- if (req.method === "PUT" || req.method === "POST") {
163
- return readBody(req).then((text) => {
164
- const body = parseBody(text);
165
- const cfg = settings.setVectorConfig({
166
- enabled: body.enabled,
167
- baseUrl: body.baseUrl,
168
- apiKey: body.apiKey,
169
- model: body.model
170
- });
171
- sendJson(res, 200, { config: cfg });
172
- });
173
- }
174
- sendJson(res, 200, { config: settings.getVectorConfig() ?? { enabled: false, baseUrl: "", apiKey: "", model: "" } });
175
- } catch {
176
- sendJson(res, 500, { error: "internal" });
177
- }
178
- }
179
- });
180
-
181
- // --- vector re-index (backfill embeddings for rows missing them) ---
182
- register({
183
- kind: "exact",
184
- path: "/api/dsh-mneme/vector-reindex",
185
- handler(req, res) {
186
- try {
187
- if (!embedder) {
188
- sendJson(res, 200, { indexed: 0, skipped: 0, error: "vector-unavailable" });
189
- return;
190
- }
191
- const url = new URL(req.url, "http://localhost");
192
- const limit = Number(url.searchParams.get("limit") ?? 100);
193
- embedder.reindexMissing(limit).then((result) => {
194
- sendJson(res, 200, result);
195
- }).catch(() => {
196
- sendJson(res, 200, { indexed: 0, skipped: 0, error: "vector-failed" });
197
- });
198
- } catch {
199
- sendJson(res, 500, { error: "internal" });
200
- }
201
- }
202
- });
203
-
204
- // --- custom commands ---
205
- register({
206
- kind: "exact",
207
- path: "/api/dsh-mneme/commands",
208
- handler(req, res) {
209
- try {
210
- if (req.method === "POST") {
211
- return readBody(req).then((text) => {
212
- const body = parseBody(text);
213
- try {
214
- const command = commands.add({
215
- name: body.name,
216
- description: body.description,
217
- instruction: body.instruction
218
- });
219
- sendJson(res, 200, { command });
220
- } catch (error) {
221
- sendJson(res, 400, { error: error.message });
222
- }
223
- });
224
- }
225
- if (req.method === "DELETE") {
226
- const url = new URL(req.url, "http://localhost");
227
- const id = url.searchParams.get("id");
228
- const removed = id ? commands.remove(id) : false;
229
- sendJson(res, 200, { removed });
230
- return;
231
- }
232
- sendJson(res, 200, { commands: commands.list() });
233
- } catch {
234
- sendJson(res, 500, { error: "internal" });
235
- }
236
- }
237
- });
238
-
239
- return {
240
- routes: 6,
241
- dispose: () => {
242
- for (const dispose of disposers) dispose();
243
- }
244
- };
245
- }
1
+ import { URL } from "node:url";
2
+
3
+ function sendJson(res, status, payload) {
4
+ res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
5
+ res.end(JSON.stringify(payload));
6
+ }
7
+
8
+ /** Collect the request body as text (tolerant of empty/invalid bodies). */
9
+ function readBody(req) {
10
+ return new Promise((resolve) => {
11
+ let body = "";
12
+ req.on("data", (chunk) => { body += chunk; });
13
+ req.on("end", () => resolve(body));
14
+ req.on("error", () => resolve(""));
15
+ });
16
+ }
17
+
18
+ function parseBody(text) {
19
+ try {
20
+ return JSON.parse(text || "{}");
21
+ } catch {
22
+ return {};
23
+ }
24
+ }
25
+
26
+ export function createApi(ctx, service, settings, commands, embedder, semantic = null) {
27
+ const disposers = [];
28
+
29
+ // Ensure the service has an embedder when the API layer was handed one
30
+ // (tests wire the embedder through the API instead of index.js). Without
31
+ // this, /api/dsh-mneme/search would silently degrade to keyword-only.
32
+ if (embedder && typeof service.setEmbedder === "function") {
33
+ service.setEmbedder(embedder);
34
+ }
35
+
36
+ const register = (route) => {
37
+ disposers.push(ctx.webServer.register(route));
38
+ };
39
+
40
+ // /api/dsh-mneme prefix fallback → 404 JSON for unknown sub-paths
41
+ register({
42
+ kind: "prefix",
43
+ path: "/api/dsh-mneme",
44
+ handler(req, res) {
45
+ sendJson(res, 404, { error: "not-found" });
46
+ }
47
+ });
48
+
49
+ register({
50
+ kind: "exact",
51
+ path: "/api/dsh-mneme/list",
52
+ handler(req, res) {
53
+ try {
54
+ const url = new URL(req.url, "http://localhost");
55
+ const type = url.searchParams.get("type") ?? undefined;
56
+ const limit = Number(url.searchParams.get("limit") ?? 50);
57
+ const offset = Number(url.searchParams.get("offset") ?? 0);
58
+ const items = service.toApiList(service.list({ type, limit, offset }));
59
+ sendJson(res, 200, { items, total: service.count(type) });
60
+ } catch {
61
+ sendJson(res, 500, { error: "internal" });
62
+ }
63
+ }
64
+ });
65
+
66
+ register({
67
+ kind: "exact",
68
+ path: "/api/dsh-mneme/search",
69
+ handler(req, res) {
70
+ try {
71
+ const url = new URL(req.url, "http://localhost");
72
+ const q = url.searchParams.get("q") ?? "";
73
+ const limit = Number(url.searchParams.get("limit") ?? 20);
74
+ // mode: auto (default) | keyword | vector | hybrid
75
+ const mode = url.searchParams.get("mode") ?? "auto";
76
+ const rerank = url.searchParams.get("rerank") !== "false";
77
+ const query = q.trim();
78
+ if (!query) {
79
+ sendJson(res, 200, { items: [], mode: "keyword" });
80
+ return;
81
+ }
82
+ // Route through the unified semantic pipeline; any vector/rerank
83
+ // failure degrades to keyword results inside searchMemories. The
84
+ // returned promise lets the test double await the async search.
85
+ return Promise.resolve(
86
+ service.searchMemories(query, { mode, topK: limit, useRerank: rerank })
87
+ ).then((rows) => {
88
+ // mode reflects what actually happened: rows marked `vector` came
89
+ // through the semantic path, everything else is keyword fallback.
90
+ const used = rows.some((m) => m.vector === true) ? "vector" : "keyword";
91
+ sendJson(res, 200, { items: service.toApiList(rows), mode: used });
92
+ }).catch(() => {
93
+ sendJson(res, 200, { items: service.toApiList(service.search(query, { limit })), mode: "keyword" });
94
+ });
95
+ } catch {
96
+ sendJson(res, 500, { error: "internal" });
97
+ }
98
+ }
99
+ });
100
+
101
+ // --- user profile ---
102
+ register({
103
+ kind: "exact",
104
+ path: "/api/dsh-mneme/profile",
105
+ handler(req, res) {
106
+ try {
107
+ if (req.method === "PUT" || req.method === "POST") {
108
+ return readBody(req).then((text) => {
109
+ const body = parseBody(text);
110
+ settings.setProfile(typeof body.profile === "string" ? body.profile : "");
111
+ sendJson(res, 200, { profile: settings.getProfile() });
112
+ });
113
+ }
114
+ sendJson(res, 200, { profile: settings.getProfile() });
115
+ } catch {
116
+ sendJson(res, 500, { error: "internal" });
117
+ }
118
+ }
119
+ });
120
+
121
+ // --- rules ---
122
+ register({
123
+ kind: "exact",
124
+ path: "/api/dsh-mneme/rules",
125
+ handler(req, res) {
126
+ try {
127
+ if (req.method === "PUT" || req.method === "POST") {
128
+ return readBody(req).then((text) => {
129
+ const body = parseBody(text);
130
+ settings.setRules(Array.isArray(body.rules) ? body.rules : []);
131
+ sendJson(res, 200, { rules: settings.getRules() });
132
+ });
133
+ }
134
+ sendJson(res, 200, { rules: settings.getRules() });
135
+ } catch {
136
+ sendJson(res, 500, { error: "internal" });
137
+ }
138
+ }
139
+ });
140
+
141
+ // --- vector search config ---
142
+ register({
143
+ kind: "exact",
144
+ path: "/api/dsh-mneme/vector-config",
145
+ handler(req, res) {
146
+ try {
147
+ if (req.method === "PUT" || req.method === "POST") {
148
+ return readBody(req).then((text) => {
149
+ const body = parseBody(text);
150
+ const cfg = settings.setVectorConfig({
151
+ enabled: body.enabled,
152
+ baseUrl: body.baseUrl,
153
+ apiKey: body.apiKey,
154
+ model: body.model
155
+ });
156
+ sendJson(res, 200, { config: cfg });
157
+ });
158
+ }
159
+ sendJson(res, 200, { config: settings.getVectorConfig() ?? { enabled: false, baseUrl: "", apiKey: "", model: "" } });
160
+ } catch {
161
+ sendJson(res, 500, { error: "internal" });
162
+ }
163
+ }
164
+ });
165
+
166
+ // --- vector re-index (backfill embeddings for rows missing them) ---
167
+ register({
168
+ kind: "exact",
169
+ path: "/api/dsh-mneme/vector-reindex",
170
+ handler(req, res) {
171
+ try {
172
+ if (!embedder) {
173
+ sendJson(res, 200, { indexed: 0, skipped: 0, error: "vector-unavailable" });
174
+ return;
175
+ }
176
+ const url = new URL(req.url, "http://localhost");
177
+ const limit = Number(url.searchParams.get("limit") ?? 100);
178
+ // Unified re-index entry: works for both the legacy OpenAI embedder and
179
+ // the new local/ollama backends (which have no reindexMissing method).
180
+ const viaIndex = semantic?.vectorIndex && semantic?.vectorIndex.rebuildIndex;
181
+ const task = viaIndex
182
+ ? semantic.vectorIndex.rebuildIndex(embedder, { limit })
183
+ : embedder.reindexMissing ? embedder.reindexMissing(limit) : Promise.resolve({ indexed: 0, skipped: 0, error: "vector-unavailable" });
184
+ task.then((result) => {
185
+ sendJson(res, 200, result);
186
+ }).catch(() => {
187
+ sendJson(res, 200, { indexed: 0, skipped: 0, error: "vector-failed" });
188
+ });
189
+ } catch {
190
+ sendJson(res, 500, { error: "internal" });
191
+ }
192
+ }
193
+ });
194
+
195
+ // --- semantic pipeline status (model, index, reranker) ---
196
+ register({
197
+ kind: "exact",
198
+ path: "/api/dsh-mneme/semantic",
199
+ handler(req, res) {
200
+ try {
201
+ const stats = semantic?.vectorIndex?.getStats?.() ?? null;
202
+ sendJson(res, 200, {
203
+ embedProvider: embedder ? (embedder.constructor?.name ?? "unknown") : null,
204
+ modelHash: embedder?.modelHash ?? null,
205
+ dimension: embedder?.dimension ?? null,
206
+ reranker: semantic?.reranker ? "ready" : null,
207
+ index: stats
208
+ });
209
+ } catch {
210
+ sendJson(res, 500, { error: "internal" });
211
+ }
212
+ }
213
+ });
214
+
215
+ // --- custom commands ---
216
+ register({
217
+ kind: "exact",
218
+ path: "/api/dsh-mneme/commands",
219
+ handler(req, res) {
220
+ try {
221
+ if (req.method === "POST") {
222
+ return readBody(req).then((text) => {
223
+ const body = parseBody(text);
224
+ try {
225
+ const command = commands.add({
226
+ name: body.name,
227
+ description: body.description,
228
+ instruction: body.instruction
229
+ });
230
+ sendJson(res, 200, { command });
231
+ } catch (error) {
232
+ sendJson(res, 400, { error: error.message });
233
+ }
234
+ });
235
+ }
236
+ if (req.method === "DELETE") {
237
+ const url = new URL(req.url, "http://localhost");
238
+ const id = url.searchParams.get("id");
239
+ const removed = id ? commands.remove(id) : false;
240
+ sendJson(res, 200, { removed });
241
+ return;
242
+ }
243
+ sendJson(res, 200, { commands: commands.list() });
244
+ } catch {
245
+ sendJson(res, 500, { error: "internal" });
246
+ }
247
+ }
248
+ });
249
+
250
+ return {
251
+ routes: 7,
252
+ dispose: () => {
253
+ for (const dispose of disposers) dispose();
254
+ }
255
+ };
256
+ }