knowmind 0.1.9
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 +17 -0
- package/README.md +70 -0
- package/bin/knowmind.js +224 -0
- package/package.json +51 -0
- package/src/client.js +115 -0
- package/src/config.js +118 -0
- package/src/extract-statements.js +134 -0
- package/src/local-embedding.js +122 -0
- package/src/mcp-stdio.js +481 -0
- package/src/sync.js +128 -0
package/src/mcp-stdio.js
ADDED
|
@@ -0,0 +1,481 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Lokaler MCP-Stdio-Server.
|
|
3
|
+
*
|
|
4
|
+
* Forwarded JSON-RPC-Requests von stdin an die Knowmind-Plattform (HTTP-MCP)
|
|
5
|
+
* und schreibt die Antworten auf stdout. Damit kann Knowmind in jeden lokalen
|
|
6
|
+
* MCP-fähigen Client (Claude Code, ChatGPT-Desktop, Cursor, ...) eingebunden
|
|
7
|
+
* werden, ohne dass der Client Bearer-Token kennen muss — der CLI-Wrapper
|
|
8
|
+
* verwaltet die Auth.
|
|
9
|
+
*
|
|
10
|
+
* Protokoll: stdio mit zeilenweise JSON (NDJSON-Style). Jedes Frame ist ein
|
|
11
|
+
* vollständiges JSON-RPC-Objekt.
|
|
12
|
+
*/
|
|
13
|
+
import { loadConfig } from "./config.js";
|
|
14
|
+
import { createInterface } from "node:readline";
|
|
15
|
+
|
|
16
|
+
// Typisierte Beziehungen zwischen Erinnerungen. Diese Liste ist die einzige
|
|
17
|
+
// Quelle der Wahrheit für Agents. Inverse-Beziehungen werden serverseitig
|
|
18
|
+
// automatisch materialisiert — der Agent setzt nur die Vorwärtsrichtung.
|
|
19
|
+
const REL_TYPES = [
|
|
20
|
+
"HAS_EMPLOYEE", "IS_EMPLOYEE_OF",
|
|
21
|
+
"IS_LED_BY", "LEADS_ORGANIZATION",
|
|
22
|
+
"OWNS", "OWNED_BY",
|
|
23
|
+
"HAS_SKILL", "WORKS_ON", "FOR_CLIENT",
|
|
24
|
+
"HAS_VERSION", "IS_VERSION_OF",
|
|
25
|
+
"HAS_CHUNK", "CHUNK_OF",
|
|
26
|
+
"HAS_EMBEDDING", "EMBEDDING_OF",
|
|
27
|
+
"INDEXED_IN",
|
|
28
|
+
"REFERENCES_ENTITY", "REFERENCED_BY",
|
|
29
|
+
"PRODUCES", "PRODUCED_BY",
|
|
30
|
+
"DEPENDS_ON", "ENABLES",
|
|
31
|
+
"APPLIES_TO", "HAS_RULE",
|
|
32
|
+
"REFERENCES", "SUPERSEDES", "SUPERSEDED_BY",
|
|
33
|
+
"WAS_GENERATED_BY", "GENERATED",
|
|
34
|
+
"USED", "USED_BY",
|
|
35
|
+
"WAS_DERIVED_FROM", "DERIVATION_TARGET_OF",
|
|
36
|
+
"WAS_ASSOCIATED_WITH",
|
|
37
|
+
"MEASURED_METRIC",
|
|
38
|
+
];
|
|
39
|
+
|
|
40
|
+
const KNOWMIND_TOOLS = [
|
|
41
|
+
{
|
|
42
|
+
name: "knowmind.recall",
|
|
43
|
+
description:
|
|
44
|
+
"Hybride Suche im Knowmind-Wissensspeicher des aktuellen Mandanten. Liefert die passendsten Treffer mit Quellenverweis und Trefferqualität.",
|
|
45
|
+
inputSchema: {
|
|
46
|
+
type: "object",
|
|
47
|
+
properties: {
|
|
48
|
+
query: { type: "string", description: "Natürlichsprachliche Frage" },
|
|
49
|
+
k: { type: "integer", minimum: 1, maximum: 25, default: 5 },
|
|
50
|
+
hops: { type: "integer", minimum: 0, maximum: 3, default: 2 },
|
|
51
|
+
},
|
|
52
|
+
required: ["query"],
|
|
53
|
+
},
|
|
54
|
+
},
|
|
55
|
+
{
|
|
56
|
+
name: "knowmind.store",
|
|
57
|
+
description:
|
|
58
|
+
"Speichert eine neue Erinnerung im aktuellen Mandanten. Liefert die Dokument-ID und die Anzahl der indexierten Abschnitte zurück. Sofort über knowmind.recall auffindbar.",
|
|
59
|
+
inputSchema: {
|
|
60
|
+
type: "object",
|
|
61
|
+
properties: {
|
|
62
|
+
title: {
|
|
63
|
+
type: "string",
|
|
64
|
+
description: "Kurzer Titel für die Erinnerung (max. 500 Zeichen)",
|
|
65
|
+
},
|
|
66
|
+
content: {
|
|
67
|
+
type: "string",
|
|
68
|
+
description: "Inhalt der Erinnerung als Text oder Markdown (max. 1 MB)",
|
|
69
|
+
},
|
|
70
|
+
},
|
|
71
|
+
required: ["title", "content"],
|
|
72
|
+
},
|
|
73
|
+
},
|
|
74
|
+
{
|
|
75
|
+
name: "knowmind.link",
|
|
76
|
+
description:
|
|
77
|
+
"Legt eine typisierte Beziehung zwischen zwei Erinnerungen an. Die Gegen-Beziehung wird automatisch mit angelegt (zum Beispiel HAS_EMPLOYEE → IS_EMPLOYEE_OF). Der Agent setzt also nur die Vorwärtsrichtung. Verwende knowmind.recall, um zuvor die IDs zu finden.",
|
|
78
|
+
inputSchema: {
|
|
79
|
+
type: "object",
|
|
80
|
+
properties: {
|
|
81
|
+
fromId: { type: "string", description: "ID der Quell-Erinnerung" },
|
|
82
|
+
toId: { type: "string", description: "ID der Ziel-Erinnerung" },
|
|
83
|
+
relType: {
|
|
84
|
+
type: "string",
|
|
85
|
+
enum: REL_TYPES,
|
|
86
|
+
description: "Beziehungstyp aus der zulässigen Liste",
|
|
87
|
+
},
|
|
88
|
+
},
|
|
89
|
+
required: ["fromId", "toId", "relType"],
|
|
90
|
+
},
|
|
91
|
+
},
|
|
92
|
+
{
|
|
93
|
+
name: "knowmind.unlink",
|
|
94
|
+
description:
|
|
95
|
+
"Entfernt eine typisierte Beziehung. Die Gegen-Beziehung wird ebenfalls gelöscht.",
|
|
96
|
+
inputSchema: {
|
|
97
|
+
type: "object",
|
|
98
|
+
properties: {
|
|
99
|
+
fromId: { type: "string" },
|
|
100
|
+
toId: { type: "string" },
|
|
101
|
+
relType: { type: "string", enum: REL_TYPES },
|
|
102
|
+
},
|
|
103
|
+
required: ["fromId", "toId", "relType"],
|
|
104
|
+
},
|
|
105
|
+
},
|
|
106
|
+
{
|
|
107
|
+
name: "knowmind.relations",
|
|
108
|
+
description:
|
|
109
|
+
"Listet alle bestehenden Beziehungen einer Erinnerung. Hilfreich bevor neue Beziehungen angelegt werden, um Duplikate zu vermeiden.",
|
|
110
|
+
inputSchema: {
|
|
111
|
+
type: "object",
|
|
112
|
+
properties: {
|
|
113
|
+
memoryId: { type: "string", description: "ID der Erinnerung" },
|
|
114
|
+
},
|
|
115
|
+
required: ["memoryId"],
|
|
116
|
+
},
|
|
117
|
+
},
|
|
118
|
+
{
|
|
119
|
+
name: "knowmind.health",
|
|
120
|
+
description: "Service-Verfügbarkeit prüfen.",
|
|
121
|
+
inputSchema: { type: "object", properties: {} },
|
|
122
|
+
},
|
|
123
|
+
{
|
|
124
|
+
name: "knowmind.stats",
|
|
125
|
+
description: "Statistik des aktuellen Mandanten (Anzahl Erinnerungen, Beziehungen).",
|
|
126
|
+
inputSchema: { type: "object", properties: {} },
|
|
127
|
+
},
|
|
128
|
+
{
|
|
129
|
+
name: "knowmind.update_fact",
|
|
130
|
+
description:
|
|
131
|
+
"Bi-temporales Update: ersetzt eine bestehende Erinnerung durch eine neue. Die alte Erinnerung bleibt im Audit-Log mit validTo=now und wird per SUPERSEDES-Beziehung mit der neuen verbunden — so bleibt die Historie nachvollziehbar. Verwende dies, wenn sich Fakten ändern (Adresse, Vertragsstatus, Personen).",
|
|
132
|
+
inputSchema: {
|
|
133
|
+
type: "object",
|
|
134
|
+
properties: {
|
|
135
|
+
targetId: { type: "string", description: "ID der zu aktualisierenden Erinnerung" },
|
|
136
|
+
newTitle: { type: "string", description: "Titel der neuen, gültigen Version" },
|
|
137
|
+
newContent: { type: "string", description: "Inhalt der neuen Version" },
|
|
138
|
+
updateReason: {
|
|
139
|
+
type: "string",
|
|
140
|
+
description: "Warum hat sich der Fakt geändert (z. B. 'Umzug', 'Vertrag erneuert')",
|
|
141
|
+
},
|
|
142
|
+
},
|
|
143
|
+
required: ["targetId", "newTitle", "newContent"],
|
|
144
|
+
},
|
|
145
|
+
},
|
|
146
|
+
{
|
|
147
|
+
name: "knowmind.recall_at_time",
|
|
148
|
+
description:
|
|
149
|
+
"Recall mit Zeitfilter: liefert nur Erinnerungen, die zum gegebenen Zeitpunkt gültig waren. Antwort auf Fragen wie 'Was wussten wir am 14. März über den Kunden?' — der Knowmind-Vorteil gegenüber reinen Vector-Stores ohne Validity-Tracking.",
|
|
150
|
+
inputSchema: {
|
|
151
|
+
type: "object",
|
|
152
|
+
properties: {
|
|
153
|
+
query: { type: "string", description: "Natürlichsprachliche Frage" },
|
|
154
|
+
asOf: {
|
|
155
|
+
type: "string",
|
|
156
|
+
description:
|
|
157
|
+
"ISO-8601-Zeitstempel des Bezugszeitpunkts (Default: jetzt). Beispiel: '2026-03-14T00:00:00Z'",
|
|
158
|
+
},
|
|
159
|
+
k: { type: "integer", minimum: 1, maximum: 25, default: 5 },
|
|
160
|
+
},
|
|
161
|
+
required: ["query"],
|
|
162
|
+
},
|
|
163
|
+
},
|
|
164
|
+
];
|
|
165
|
+
|
|
166
|
+
/** Hilfsfunktion: ruft einen REST-Endpunkt mit Bearer-Token auf und verpackt
|
|
167
|
+
* die Antwort im MCP-Tool-Result-Format. */
|
|
168
|
+
async function restCall(apiUrl, token, path, init) {
|
|
169
|
+
const r = await fetch(`${apiUrl}${path}`, {
|
|
170
|
+
...init,
|
|
171
|
+
headers: {
|
|
172
|
+
"content-type": "application/json",
|
|
173
|
+
authorization: `Bearer ${token}`,
|
|
174
|
+
...(init?.headers ?? {}),
|
|
175
|
+
},
|
|
176
|
+
});
|
|
177
|
+
let data;
|
|
178
|
+
try {
|
|
179
|
+
data = await r.json();
|
|
180
|
+
} catch {
|
|
181
|
+
data = { error: `HTTP ${r.status}` };
|
|
182
|
+
}
|
|
183
|
+
if (!r.ok) {
|
|
184
|
+
return {
|
|
185
|
+
error: {
|
|
186
|
+
code: -32000,
|
|
187
|
+
message: data.error ?? `HTTP ${r.status}`,
|
|
188
|
+
data,
|
|
189
|
+
},
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
return {
|
|
193
|
+
result: {
|
|
194
|
+
content: [{ type: "text", text: JSON.stringify(data) }],
|
|
195
|
+
},
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
async function callRestTool(apiUrl, token, name, args) {
|
|
200
|
+
switch (name) {
|
|
201
|
+
case "knowmind.store": {
|
|
202
|
+
const { title, content } = args;
|
|
203
|
+
if (!title || !content) {
|
|
204
|
+
return {
|
|
205
|
+
error: {
|
|
206
|
+
code: -32602,
|
|
207
|
+
message: "knowmind.store benötigt title und content.",
|
|
208
|
+
},
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
return await restCall(apiUrl, token, "/api/documents", {
|
|
212
|
+
method: "POST",
|
|
213
|
+
body: JSON.stringify({ title, content }),
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
case "knowmind.link": {
|
|
217
|
+
const { fromId, toId, relType } = args;
|
|
218
|
+
if (!fromId || !toId || !relType) {
|
|
219
|
+
return {
|
|
220
|
+
error: {
|
|
221
|
+
code: -32602,
|
|
222
|
+
message: "knowmind.link benötigt fromId, toId, relType.",
|
|
223
|
+
},
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
return await restCall(apiUrl, token, "/api/graph/relations", {
|
|
227
|
+
method: "POST",
|
|
228
|
+
body: JSON.stringify({ fromId, toId, relType }),
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
case "knowmind.unlink": {
|
|
232
|
+
const { fromId, toId, relType } = args;
|
|
233
|
+
if (!fromId || !toId || !relType) {
|
|
234
|
+
return {
|
|
235
|
+
error: {
|
|
236
|
+
code: -32602,
|
|
237
|
+
message: "knowmind.unlink benötigt fromId, toId, relType.",
|
|
238
|
+
},
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
const params = new URLSearchParams({ fromId, toId, relType });
|
|
242
|
+
return await restCall(apiUrl, token, `/api/graph/relations?${params.toString()}`, {
|
|
243
|
+
method: "DELETE",
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
case "knowmind.relations": {
|
|
247
|
+
const { memoryId } = args;
|
|
248
|
+
if (!memoryId) {
|
|
249
|
+
return {
|
|
250
|
+
error: {
|
|
251
|
+
code: -32602,
|
|
252
|
+
message: "knowmind.relations benötigt memoryId.",
|
|
253
|
+
},
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
const params = new URLSearchParams({ memoryId });
|
|
257
|
+
return await restCall(apiUrl, token, `/api/graph/relations?${params.toString()}`, {
|
|
258
|
+
method: "GET",
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
default:
|
|
262
|
+
return {
|
|
263
|
+
error: { code: -32601, message: `Unknown tool: ${name}` },
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
async function forwardToServer(method, params) {
|
|
269
|
+
const { apiUrl, token } = loadConfig();
|
|
270
|
+
if (!token)
|
|
271
|
+
throw new Error("Knowmind: kein Token konfiguriert. `knowmind login` zuerst.");
|
|
272
|
+
|
|
273
|
+
// Tools, die nicht über den MCP-Endpoint, sondern direkt gegen die
|
|
274
|
+
// REST-Schnittstelle laufen (Anlegen + Graph-Beziehungen).
|
|
275
|
+
if (
|
|
276
|
+
method === "tools/call" &&
|
|
277
|
+
params &&
|
|
278
|
+
typeof params.name === "string" &&
|
|
279
|
+
["knowmind.store", "knowmind.link", "knowmind.unlink", "knowmind.relations"].includes(
|
|
280
|
+
params.name,
|
|
281
|
+
)
|
|
282
|
+
) {
|
|
283
|
+
return await callRestTool(apiUrl, token, params.name, params.arguments ?? {});
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
const r = await fetch(`${apiUrl}/api/mcp/v1`, {
|
|
287
|
+
method: "POST",
|
|
288
|
+
headers: {
|
|
289
|
+
"content-type": "application/json",
|
|
290
|
+
authorization: `Bearer ${token}`,
|
|
291
|
+
},
|
|
292
|
+
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
|
|
293
|
+
});
|
|
294
|
+
return await r.json();
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function write(obj) {
|
|
298
|
+
process.stdout.write(JSON.stringify(obj) + "\n");
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* Probiert den konfigurierten Token gegen den Server. Liefert
|
|
303
|
+
* { ok: true } oder { ok: false, reason: "..." }. Wird in der
|
|
304
|
+
* `initialize`-Phase aufgerufen, damit der MCP-Client (Claude Code,
|
|
305
|
+
* Codex, Cursor) bei ungültigem Token NICHT „connected ✓" anzeigt,
|
|
306
|
+
* sondern eine klare Fehlermeldung.
|
|
307
|
+
*/
|
|
308
|
+
async function probeAuth() {
|
|
309
|
+
let cfg;
|
|
310
|
+
try {
|
|
311
|
+
cfg = loadConfig();
|
|
312
|
+
} catch (e) {
|
|
313
|
+
return { ok: false, reason: `Config nicht lesbar: ${e.message}` };
|
|
314
|
+
}
|
|
315
|
+
if (!cfg.token) {
|
|
316
|
+
return {
|
|
317
|
+
ok: false,
|
|
318
|
+
reason:
|
|
319
|
+
"Kein Knowmind-Token konfiguriert. Bitte `knowmind login` im Terminal ausführen.",
|
|
320
|
+
};
|
|
321
|
+
}
|
|
322
|
+
if (!cfg.token.startsWith("kmt_")) {
|
|
323
|
+
return {
|
|
324
|
+
ok: false,
|
|
325
|
+
reason:
|
|
326
|
+
"Konfigurierter Token hat ein ungültiges Format (erwartet: kmt_…). Bitte `knowmind login` neu ausführen.",
|
|
327
|
+
};
|
|
328
|
+
}
|
|
329
|
+
try {
|
|
330
|
+
const r = await fetch(`${cfg.apiUrl}/api/mcp/v1`, {
|
|
331
|
+
method: "POST",
|
|
332
|
+
headers: {
|
|
333
|
+
"content-type": "application/json",
|
|
334
|
+
authorization: `Bearer ${cfg.token}`,
|
|
335
|
+
},
|
|
336
|
+
body: JSON.stringify({
|
|
337
|
+
jsonrpc: "2.0",
|
|
338
|
+
id: 1,
|
|
339
|
+
method: "tools/call",
|
|
340
|
+
params: { name: "knowmind.health", arguments: {} },
|
|
341
|
+
}),
|
|
342
|
+
});
|
|
343
|
+
if (!r.ok) {
|
|
344
|
+
return {
|
|
345
|
+
ok: false,
|
|
346
|
+
reason:
|
|
347
|
+
`Knowmind-Server antwortet mit HTTP ${r.status}. Token wahrscheinlich abgelaufen — bitte "knowmind login" neu ausführen.`,
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
const data = await r.json();
|
|
351
|
+
if (data.error) {
|
|
352
|
+
return {
|
|
353
|
+
ok: false,
|
|
354
|
+
reason:
|
|
355
|
+
`Knowmind-Server lehnt Token ab: ${data.error.message ?? "unbekannter Grund"}. Bitte "knowmind login" neu ausführen.`,
|
|
356
|
+
};
|
|
357
|
+
}
|
|
358
|
+
return { ok: true };
|
|
359
|
+
} catch (e) {
|
|
360
|
+
return {
|
|
361
|
+
ok: false,
|
|
362
|
+
reason: `Knowmind-Server nicht erreichbar (${cfg.apiUrl}): ${e.message}`,
|
|
363
|
+
};
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
export async function runStdioServer() {
|
|
368
|
+
// Auth einmal am Start prüfen. Das Ergebnis cachen — der MCP-Client
|
|
369
|
+
// soll sofort beim initialize wissen, ob die Verbindung wirklich
|
|
370
|
+
// steht.
|
|
371
|
+
const auth = await probeAuth();
|
|
372
|
+
if (!auth.ok) {
|
|
373
|
+
process.stderr.write(`[knowmind] AUTH-FEHLER: ${auth.reason}\n`);
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
const rl = createInterface({ input: process.stdin });
|
|
377
|
+
for await (const line of rl) {
|
|
378
|
+
const trimmed = line.trim();
|
|
379
|
+
if (!trimmed) continue;
|
|
380
|
+
let req;
|
|
381
|
+
try {
|
|
382
|
+
req = JSON.parse(trimmed);
|
|
383
|
+
} catch {
|
|
384
|
+
write({
|
|
385
|
+
jsonrpc: "2.0",
|
|
386
|
+
id: null,
|
|
387
|
+
error: { code: -32700, message: "Parse error" },
|
|
388
|
+
});
|
|
389
|
+
continue;
|
|
390
|
+
}
|
|
391
|
+
try {
|
|
392
|
+
switch (req.method) {
|
|
393
|
+
case "initialize":
|
|
394
|
+
if (!auth.ok) {
|
|
395
|
+
// Initialize FEHLSCHLAGEN, damit der MCP-Client „connected"
|
|
396
|
+
// nicht fälschlich anzeigt. Claude Code, Codex und Cursor
|
|
397
|
+
// werten -32001 als harte Connection-Failure.
|
|
398
|
+
write({
|
|
399
|
+
jsonrpc: "2.0",
|
|
400
|
+
id: req.id ?? null,
|
|
401
|
+
error: {
|
|
402
|
+
code: -32001,
|
|
403
|
+
message: `Knowmind nicht verbunden: ${auth.reason}`,
|
|
404
|
+
},
|
|
405
|
+
});
|
|
406
|
+
break;
|
|
407
|
+
}
|
|
408
|
+
write({
|
|
409
|
+
jsonrpc: "2.0",
|
|
410
|
+
id: req.id ?? null,
|
|
411
|
+
result: {
|
|
412
|
+
protocolVersion: "2025-06-18",
|
|
413
|
+
serverInfo: { name: "knowmind", version: "0.1.5" },
|
|
414
|
+
capabilities: { tools: {} },
|
|
415
|
+
},
|
|
416
|
+
});
|
|
417
|
+
break;
|
|
418
|
+
case "tools/list":
|
|
419
|
+
if (!auth.ok) {
|
|
420
|
+
write({
|
|
421
|
+
jsonrpc: "2.0",
|
|
422
|
+
id: req.id ?? null,
|
|
423
|
+
error: {
|
|
424
|
+
code: -32001,
|
|
425
|
+
message: `Knowmind nicht verbunden: ${auth.reason}`,
|
|
426
|
+
},
|
|
427
|
+
});
|
|
428
|
+
break;
|
|
429
|
+
}
|
|
430
|
+
write({
|
|
431
|
+
jsonrpc: "2.0",
|
|
432
|
+
id: req.id ?? null,
|
|
433
|
+
result: { tools: KNOWMIND_TOOLS },
|
|
434
|
+
});
|
|
435
|
+
break;
|
|
436
|
+
case "tools/call": {
|
|
437
|
+
if (!auth.ok) {
|
|
438
|
+
write({
|
|
439
|
+
jsonrpc: "2.0",
|
|
440
|
+
id: req.id ?? null,
|
|
441
|
+
error: {
|
|
442
|
+
code: -32001,
|
|
443
|
+
message: `Knowmind nicht verbunden: ${auth.reason}`,
|
|
444
|
+
},
|
|
445
|
+
});
|
|
446
|
+
break;
|
|
447
|
+
}
|
|
448
|
+
const upstream = await forwardToServer(req.method, req.params);
|
|
449
|
+
// Upstream-Response hat eigene jsonrpc/id-Felder — die müssen
|
|
450
|
+
// durch die Client-id ersetzt werden, damit Claude Code, Codex
|
|
451
|
+
// und Gemini ihre Anfragen korrekt zuordnen können.
|
|
452
|
+
const response = {
|
|
453
|
+
jsonrpc: "2.0",
|
|
454
|
+
id: req.id ?? null,
|
|
455
|
+
};
|
|
456
|
+
if (upstream && typeof upstream === "object" && "result" in upstream) {
|
|
457
|
+
response.result = upstream.result;
|
|
458
|
+
} else if (upstream && typeof upstream === "object" && "error" in upstream) {
|
|
459
|
+
response.error = upstream.error;
|
|
460
|
+
} else {
|
|
461
|
+
response.result = upstream;
|
|
462
|
+
}
|
|
463
|
+
write(response);
|
|
464
|
+
break;
|
|
465
|
+
}
|
|
466
|
+
default:
|
|
467
|
+
write({
|
|
468
|
+
jsonrpc: "2.0",
|
|
469
|
+
id: req.id ?? null,
|
|
470
|
+
error: { code: -32601, message: `Method not found: ${req.method}` },
|
|
471
|
+
});
|
|
472
|
+
}
|
|
473
|
+
} catch (e) {
|
|
474
|
+
write({
|
|
475
|
+
jsonrpc: "2.0",
|
|
476
|
+
id: req?.id ?? null,
|
|
477
|
+
error: { code: -32603, message: e instanceof Error ? e.message : String(e) },
|
|
478
|
+
});
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
}
|
package/src/sync.js
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `knowmind sync <directory>` — synchronisiert einen lokalen Ordner mit dem
|
|
3
|
+
* Knowmind-Korpus. Idempotent: bereits hochgeladene und unveränderte Dateien
|
|
4
|
+
* werden über einen Manifest-Vergleich übersprungen.
|
|
5
|
+
*
|
|
6
|
+
* Manifest: `<directory>/.knowmind-manifest.json`
|
|
7
|
+
* { "files": { "<relpath>": { sha256, documentId, lastSync } },
|
|
8
|
+
* "version": 1 }
|
|
9
|
+
*
|
|
10
|
+
* Server-seitige Dedup (HTTP 200 + duplicate:true) wird als Erfolg behandelt
|
|
11
|
+
* und das Manifest aktualisiert.
|
|
12
|
+
*/
|
|
13
|
+
import { readFileSync, readdirSync, statSync, writeFileSync, existsSync } from "node:fs";
|
|
14
|
+
import { join, relative, basename, extname } from "node:path";
|
|
15
|
+
import { createHash } from "node:crypto";
|
|
16
|
+
import { uploadDocument } from "./client.js";
|
|
17
|
+
|
|
18
|
+
const DEFAULT_EXTENSIONS = [".md", ".markdown", ".txt"];
|
|
19
|
+
const MANIFEST_NAME = ".knowmind-manifest.json";
|
|
20
|
+
const IGNORE_DIRS = new Set([
|
|
21
|
+
"node_modules", ".git", ".next", "dist", "build",
|
|
22
|
+
".venv", "venv", "__pycache__", ".cache",
|
|
23
|
+
]);
|
|
24
|
+
|
|
25
|
+
function* walk(root, exts) {
|
|
26
|
+
const entries = readdirSync(root, { withFileTypes: true });
|
|
27
|
+
for (const e of entries) {
|
|
28
|
+
if (e.name.startsWith(".") && e.name !== ".") continue;
|
|
29
|
+
const full = join(root, e.name);
|
|
30
|
+
if (e.isDirectory()) {
|
|
31
|
+
if (IGNORE_DIRS.has(e.name)) continue;
|
|
32
|
+
yield* walk(full, exts);
|
|
33
|
+
} else if (e.isFile()) {
|
|
34
|
+
const ext = extname(e.name).toLowerCase();
|
|
35
|
+
if (exts.includes(ext)) yield full;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function sha256(content) {
|
|
41
|
+
return createHash("sha256").update(content, "utf-8").digest("hex");
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function loadManifest(path) {
|
|
45
|
+
if (!existsSync(path)) return { version: 1, files: {} };
|
|
46
|
+
try {
|
|
47
|
+
const data = JSON.parse(readFileSync(path, "utf-8"));
|
|
48
|
+
return data && data.version === 1 && data.files ? data : { version: 1, files: {} };
|
|
49
|
+
} catch {
|
|
50
|
+
return { version: 1, files: {} };
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function saveManifest(path, manifest) {
|
|
55
|
+
writeFileSync(path, JSON.stringify(manifest, null, 2));
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function deriveTitle(content, filePath) {
|
|
59
|
+
const m = content.match(/^#\s+(.+)$/m);
|
|
60
|
+
if (m) return m[1].trim();
|
|
61
|
+
const m2 = content.match(/^name:\s*([^\n\r]+)$/m);
|
|
62
|
+
if (m2) return m2[1].trim();
|
|
63
|
+
return basename(filePath, extname(filePath));
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export async function syncDirectory(dir, options = {}) {
|
|
67
|
+
if (!existsSync(dir) || !statSync(dir).isDirectory()) {
|
|
68
|
+
throw new Error(`Verzeichnis nicht gefunden: ${dir}`);
|
|
69
|
+
}
|
|
70
|
+
const exts = options.extensions ?? DEFAULT_EXTENSIONS;
|
|
71
|
+
const manifestPath = join(dir, MANIFEST_NAME);
|
|
72
|
+
const manifest = loadManifest(manifestPath);
|
|
73
|
+
|
|
74
|
+
const files = [...walk(dir, exts)].sort();
|
|
75
|
+
const total = files.length;
|
|
76
|
+
let scanned = 0;
|
|
77
|
+
let uploaded = 0;
|
|
78
|
+
let skipped = 0;
|
|
79
|
+
let failed = 0;
|
|
80
|
+
const failures = [];
|
|
81
|
+
|
|
82
|
+
console.log(`Knowmind sync: ${total} Dateien in ${dir}`);
|
|
83
|
+
|
|
84
|
+
for (const file of files) {
|
|
85
|
+
scanned += 1;
|
|
86
|
+
const rel = relative(dir, file).replace(/\\/g, "/");
|
|
87
|
+
if (basename(file) === MANIFEST_NAME) continue;
|
|
88
|
+
const content = readFileSync(file, "utf-8");
|
|
89
|
+
const hash = sha256(content);
|
|
90
|
+
const known = manifest.files[rel];
|
|
91
|
+
|
|
92
|
+
if (known && known.sha256 === hash) {
|
|
93
|
+
skipped += 1;
|
|
94
|
+
if (options.verbose) console.log(` skip ${rel}`);
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const title = options.titleFromContent ? deriveTitle(content, file) : basename(file, extname(file));
|
|
99
|
+
try {
|
|
100
|
+
const result = await uploadDocument(title, content);
|
|
101
|
+
uploaded += 1;
|
|
102
|
+
manifest.files[rel] = {
|
|
103
|
+
sha256: hash,
|
|
104
|
+
documentId: result.id ?? null,
|
|
105
|
+
lastSync: new Date().toISOString(),
|
|
106
|
+
duplicate: Boolean(result.duplicate),
|
|
107
|
+
};
|
|
108
|
+
// Manifest regelmäßig zwischenspeichern, damit ein Abbruch mid-run
|
|
109
|
+
// nicht alle Fortschritte verliert.
|
|
110
|
+
if (uploaded % 10 === 0) saveManifest(manifestPath, manifest);
|
|
111
|
+
const flag = result.duplicate ? "dup " : "new ";
|
|
112
|
+
process.stdout.write(` [${scanned}/${total}] ${flag} ${rel}\n`);
|
|
113
|
+
} catch (e) {
|
|
114
|
+
failed += 1;
|
|
115
|
+
failures.push({ file: rel, error: e.message });
|
|
116
|
+
process.stderr.write(` [${scanned}/${total}] FAIL ${rel} — ${e.message}\n`);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
saveManifest(manifestPath, manifest);
|
|
121
|
+
console.log(`\nFertig: ${uploaded} hochgeladen, ${skipped} unverändert, ${failed} fehlerhaft.`);
|
|
122
|
+
if (failed > 0) {
|
|
123
|
+
console.log(`Fehler-Übersicht (max 10):`);
|
|
124
|
+
failures.slice(0, 10).forEach((f) => console.log(` ${f.file}: ${f.error}`));
|
|
125
|
+
return { uploaded, skipped, failed, failures };
|
|
126
|
+
}
|
|
127
|
+
return { uploaded, skipped, failed, failures };
|
|
128
|
+
}
|