knowmind 0.3.6 → 0.3.7

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.
@@ -1,66 +1,66 @@
1
- /**
2
- * Vergleicht die mitgelieferte Werkzeugliste mit der öffentlichen Discovery.
3
- *
4
- * `src/tools-fallback.json` ist der Rückfall, wenn der Weg zu knowmind.de
5
- * versperrt ist — eine Sandbox ohne Netz, ein Verzeichnis-Crawler hinter einer
6
- * Firewall. Ohne ihn sieht eine Inspektion kein einziges Werkzeug und hält den
7
- * Server für leer.
8
- *
9
- * Der Rückfall veraltet, sobald der Server ein Werkzeug bekommt oder ein
10
- * Eingabeschema ändert. Dieser Abgleich schlägt dann an. Er gehört in die
11
- * Pipeline und vor jedes Release.
12
- *
13
- * node scripts/tools-abgleich.mjs
14
- *
15
- * Rückgabewert 1, wenn die Listen auseinanderlaufen; 0, wenn sie gleich sind.
16
- * Ist die Discovery nicht erreichbar, endet der Lauf mit 2 — dann sagt er
17
- * nichts über den Rückfall aus und darf nicht als bestanden gelten.
18
- */
19
- import { readFileSync } from "node:fs";
20
-
21
- const QUELLE = "https://knowmind.de/api/mcp/v1";
22
-
23
- const datei = JSON.parse(
24
- readFileSync(new URL("../src/tools-fallback.json", import.meta.url), "utf8"),
25
- );
26
-
27
- let live;
28
- try {
29
- const r = await fetch(QUELLE, { headers: { accept: "application/json" } });
30
- if (!r.ok) throw new Error(`HTTP ${r.status}`);
31
- live = await r.json();
32
- } catch (e) {
33
- console.error(`Discovery nicht erreichbar (${QUELLE}): ${e.message}`);
34
- console.error("Der Abgleich sagt damit nichts über den Rückfall aus.");
35
- process.exit(2);
36
- }
37
-
38
- const namen = (liste) => (liste ?? []).map((w) => w.name).sort();
39
- const alt = namen(datei.tools);
40
- const neu = namen(live.tools);
41
-
42
- const fehlen = neu.filter((n) => !alt.includes(n));
43
- const zuviel = alt.filter((n) => !neu.includes(n));
44
-
45
- // Ein Werkzeug kann denselben Namen tragen und ein anderes Eingabeschema haben.
46
- const schema = (liste, name) =>
47
- JSON.stringify((liste ?? []).find((w) => w.name === name)?.inputSchema ?? {});
48
- const geaendert = neu
49
- .filter((n) => alt.includes(n))
50
- .filter((n) => schema(datei.tools, n) !== schema(live.tools, n));
51
-
52
- if (fehlen.length === 0 && zuviel.length === 0 && geaendert.length === 0) {
53
- console.log(
54
- `Rückfall aktuell: ${alt.length} Werkzeuge, Stand ${datei.stand}, Schemas gleich.`,
55
- );
56
- process.exit(0);
57
- }
58
-
59
- console.error(`Rückfall veraltet (Stand ${datei.stand}):`);
60
- if (fehlen.length) console.error(` fehlen: ${fehlen.join(", ")}`);
61
- if (zuviel.length) console.error(` überzählig: ${zuviel.join(", ")}`);
62
- if (geaendert.length)
63
- console.error(` Schema neu: ${geaendert.join(", ")}`);
64
- console.error("");
65
- console.error("Neu erzeugen und die Änderung mit einem Release ausliefern.");
66
- process.exit(1);
1
+ /**
2
+ * Vergleicht die mitgelieferte Werkzeugliste mit der öffentlichen Discovery.
3
+ *
4
+ * `src/tools-fallback.json` ist der Rückfall, wenn der Weg zu knowmind.de
5
+ * versperrt ist — eine Sandbox ohne Netz, ein Verzeichnis-Crawler hinter einer
6
+ * Firewall. Ohne ihn sieht eine Inspektion kein einziges Werkzeug und hält den
7
+ * Server für leer.
8
+ *
9
+ * Der Rückfall veraltet, sobald der Server ein Werkzeug bekommt oder ein
10
+ * Eingabeschema ändert. Dieser Abgleich schlägt dann an. Er gehört in die
11
+ * Pipeline und vor jedes Release.
12
+ *
13
+ * node scripts/tools-abgleich.mjs
14
+ *
15
+ * Rückgabewert 1, wenn die Listen auseinanderlaufen; 0, wenn sie gleich sind.
16
+ * Ist die Discovery nicht erreichbar, endet der Lauf mit 2 — dann sagt er
17
+ * nichts über den Rückfall aus und darf nicht als bestanden gelten.
18
+ */
19
+ import { readFileSync } from "node:fs";
20
+
21
+ const QUELLE = "https://knowmind.de/api/mcp/v1";
22
+
23
+ const datei = JSON.parse(
24
+ readFileSync(new URL("../src/tools-fallback.json", import.meta.url), "utf8"),
25
+ );
26
+
27
+ let live;
28
+ try {
29
+ const r = await fetch(QUELLE, { headers: { accept: "application/json" } });
30
+ if (!r.ok) throw new Error(`HTTP ${r.status}`);
31
+ live = await r.json();
32
+ } catch (e) {
33
+ console.error(`Discovery nicht erreichbar (${QUELLE}): ${e.message}`);
34
+ console.error("Der Abgleich sagt damit nichts über den Rückfall aus.");
35
+ process.exit(2);
36
+ }
37
+
38
+ const namen = (liste) => (liste ?? []).map((w) => w.name).sort();
39
+ const alt = namen(datei.tools);
40
+ const neu = namen(live.tools);
41
+
42
+ const fehlen = neu.filter((n) => !alt.includes(n));
43
+ const zuviel = alt.filter((n) => !neu.includes(n));
44
+
45
+ // Ein Werkzeug kann denselben Namen tragen und ein anderes Eingabeschema haben.
46
+ const schema = (liste, name) =>
47
+ JSON.stringify((liste ?? []).find((w) => w.name === name)?.inputSchema ?? {});
48
+ const geaendert = neu
49
+ .filter((n) => alt.includes(n))
50
+ .filter((n) => schema(datei.tools, n) !== schema(live.tools, n));
51
+
52
+ if (fehlen.length === 0 && zuviel.length === 0 && geaendert.length === 0) {
53
+ console.log(
54
+ `Rückfall aktuell: ${alt.length} Werkzeuge, Stand ${datei.stand}, Schemas gleich.`,
55
+ );
56
+ process.exit(0);
57
+ }
58
+
59
+ console.error(`Rückfall veraltet (Stand ${datei.stand}):`);
60
+ if (fehlen.length) console.error(` fehlen: ${fehlen.join(", ")}`);
61
+ if (zuviel.length) console.error(` überzählig: ${zuviel.join(", ")}`);
62
+ if (geaendert.length)
63
+ console.error(` Schema neu: ${geaendert.join(", ")}`);
64
+ console.error("");
65
+ console.error("Neu erzeugen und die Änderung mit einem Release ausliefern.");
66
+ process.exit(1);
package/src/client.js CHANGED
@@ -1,143 +1,143 @@
1
- /**
2
- * Knowmind-API-Client.
3
- *
4
- * Spricht ausschließlich gegen den MCP-Endpoint /api/mcp/v1 (JSON-RPC),
5
- * weil dieser bereits Bearer-Auth + Tools für recall/stats/health bietet.
6
- * Document-Upload geht zusätzlich gegen die REST-API /api/documents.
7
- */
8
- import { loadConfig } from "./config.js";
9
-
10
- let rpcId = 1;
11
-
12
- async function rpc(method, params, options = {}) {
13
- const { apiUrl, token } = loadConfig();
14
- if (!token) throw new Error("Kein Token konfiguriert — bitte `knowmind login` ausführen.");
15
- const r = await fetch(`${apiUrl}/api/mcp/v1`, {
16
- method: "POST",
17
- headers: {
18
- "content-type": "application/json",
19
- authorization: `Bearer ${token}`,
20
- ...(options.headers ?? {}),
21
- },
22
- body: JSON.stringify({ jsonrpc: "2.0", id: rpcId++, method, params }),
23
- signal: options.signal,
24
- });
25
- const data = await r.json();
26
- if (data.error) throw new Error(`${data.error.code}: ${data.error.message}`);
27
- return data.result;
28
- }
29
-
30
- /**
31
- * Tool-Text tolerant parsen: Server-Versionen vom 16.07.2026 stellten dem
32
- * JSON zeitweise einen Präsenz-Marker („● knowmind · N Treffer") voran.
33
- * Erst direkt parsen, sonst ab der ersten öffnenden Klammer.
34
- */
35
- function parseToolJson(text) {
36
- try {
37
- return JSON.parse(text);
38
- } catch (err) {
39
- for (const ch of ["{", "["]) {
40
- const i = text.indexOf(ch);
41
- if (i >= 0) {
42
- try {
43
- return JSON.parse(text.slice(i));
44
- } catch {
45
- /* nächster Kandidat */
46
- }
47
- }
48
- }
49
- throw err;
50
- }
51
- }
52
-
53
- export async function recall(query, { k = 5, hops = 2 } = {}) {
54
- const res = await rpc("tools/call", {
55
- name: "knowmind_recall",
56
- arguments: { query, k, hops },
57
- });
58
- // MCP-Antwort: { content: [{ type: "text", text: "<JSON>" }] }
59
- const text = res.content?.[0]?.text;
60
- if (!text) return null;
61
- return parseToolJson(text);
62
- }
63
-
64
- export async function stats() {
65
- const res = await rpc("tools/call", { name: "knowmind_stats", arguments: {} });
66
- return parseToolJson(res.content?.[0]?.text ?? "{}");
67
- }
68
-
69
- export async function health() {
70
- const res = await rpc("tools/call", { name: "knowmind_health", arguments: {} });
71
- return parseToolJson(res.content?.[0]?.text ?? "{}");
72
- }
73
-
74
- /**
75
- * Lädt ein Dokument hoch. Default-Pfad: Client rechnet die Embeddings
76
- * lokal und schickt sie mit — der Server speichert nur noch, ohne eigene
77
- * Berechnung. Skaliert deutlich besser.
78
- *
79
- * Wird KNOWMIND_EMBED_MODE=server gesetzt, geht der alte Pfad: Server
80
- * rechnet selbst. Sinnvoll als Fallback, wenn der Client kein Modell
81
- * laden kann (z. B. RAM-knapp).
82
- */
83
- export async function uploadDocument(title, content, opts = {}) {
84
- const { apiUrl, token } = loadConfig();
85
- if (!token) throw new Error("Kein Token konfiguriert.");
86
-
87
- const mode = (process.env.KNOWMIND_EMBED_MODE || "client").toLowerCase();
88
- let body;
89
- if (mode === "client") {
90
- try {
91
- const { prepareChunks, embedBatch, MODEL } = await import("./local-embedding.js");
92
- // prepareChunks zerlegt Text in Standard-Chunks UND extrahiert
93
- // Preference-/Fact-/Update-Statements als Zusatz-Chunks mit type-Tag.
94
- // Recall-Server boostet die getaggten Chunks für passende Queries.
95
- const prepared = await prepareChunks(content);
96
- const vectors = await embedBatch(prepared.map((c) => c.content), "passage");
97
- body = {
98
- title,
99
- content,
100
- chunks: prepared.map((c, i) => ({
101
- content: c.content,
102
- embedding: vectors[i],
103
- ...(c.metadata ? { metadata: c.metadata } : {}),
104
- })),
105
- embeddingModel: MODEL,
106
- };
107
- } catch (err) {
108
- process.stderr.write(
109
- `[knowmind] lokales Embedding fehlgeschlagen, fallback auf Server: ${err.message}\n`,
110
- );
111
- body = { title, content };
112
- }
113
- } else {
114
- body = { title, content };
115
- }
116
-
117
- // Upsert per documentId: kennt der Sync aus dem Manifest die Vorgaenger-
118
- // documentId, geht sie als replaceDocumentId mit — der Server ersetzt damit
119
- // genau diese Alt-Version, titelunabhaengig (verhindert Titel-Dubletten).
120
- if (opts.replaceDocumentId) body.replaceDocumentId = opts.replaceDocumentId;
121
-
122
- const r = await fetch(`${apiUrl}/api/documents`, {
123
- method: "POST",
124
- headers: { "content-type": "application/json", authorization: `Bearer ${token}` },
125
- body: JSON.stringify(body),
126
- });
127
- const text = await r.text();
128
- let data;
129
- try {
130
- data = text ? JSON.parse(text) : {};
131
- } catch {
132
- if (!r.ok) {
133
- throw new Error(`HTTP ${r.status} ${r.statusText} — ${text.slice(0, 200)}`);
134
- }
135
- throw new Error(`HTTP ${r.status} lieferte ungültiges JSON: ${text.slice(0, 200)}`);
136
- }
137
- if (!r.ok) throw new Error(data.error ?? `HTTP ${r.status} ${r.statusText}`);
138
- return data;
139
- }
140
-
141
- export async function listTools() {
142
- return await rpc("tools/list", {});
143
- }
1
+ /**
2
+ * Knowmind-API-Client.
3
+ *
4
+ * Spricht ausschließlich gegen den MCP-Endpoint /api/mcp/v1 (JSON-RPC),
5
+ * weil dieser bereits Bearer-Auth + Tools für recall/stats/health bietet.
6
+ * Document-Upload geht zusätzlich gegen die REST-API /api/documents.
7
+ */
8
+ import { loadConfig } from "./config.js";
9
+
10
+ let rpcId = 1;
11
+
12
+ async function rpc(method, params, options = {}) {
13
+ const { apiUrl, token } = loadConfig();
14
+ if (!token) throw new Error("Kein Token konfiguriert — bitte `knowmind login` ausführen.");
15
+ const r = await fetch(`${apiUrl}/api/mcp/v1`, {
16
+ method: "POST",
17
+ headers: {
18
+ "content-type": "application/json",
19
+ authorization: `Bearer ${token}`,
20
+ ...(options.headers ?? {}),
21
+ },
22
+ body: JSON.stringify({ jsonrpc: "2.0", id: rpcId++, method, params }),
23
+ signal: options.signal,
24
+ });
25
+ const data = await r.json();
26
+ if (data.error) throw new Error(`${data.error.code}: ${data.error.message}`);
27
+ return data.result;
28
+ }
29
+
30
+ /**
31
+ * Tool-Text tolerant parsen: Server-Versionen vom 16.07.2026 stellten dem
32
+ * JSON zeitweise einen Präsenz-Marker („● knowmind · N Treffer") voran.
33
+ * Erst direkt parsen, sonst ab der ersten öffnenden Klammer.
34
+ */
35
+ function parseToolJson(text) {
36
+ try {
37
+ return JSON.parse(text);
38
+ } catch (err) {
39
+ for (const ch of ["{", "["]) {
40
+ const i = text.indexOf(ch);
41
+ if (i >= 0) {
42
+ try {
43
+ return JSON.parse(text.slice(i));
44
+ } catch {
45
+ /* nächster Kandidat */
46
+ }
47
+ }
48
+ }
49
+ throw err;
50
+ }
51
+ }
52
+
53
+ export async function recall(query, { k = 5, hops = 2 } = {}) {
54
+ const res = await rpc("tools/call", {
55
+ name: "knowmind_recall",
56
+ arguments: { query, k, hops },
57
+ });
58
+ // MCP-Antwort: { content: [{ type: "text", text: "<JSON>" }] }
59
+ const text = res.content?.[0]?.text;
60
+ if (!text) return null;
61
+ return parseToolJson(text);
62
+ }
63
+
64
+ export async function stats() {
65
+ const res = await rpc("tools/call", { name: "knowmind_stats", arguments: {} });
66
+ return parseToolJson(res.content?.[0]?.text ?? "{}");
67
+ }
68
+
69
+ export async function health() {
70
+ const res = await rpc("tools/call", { name: "knowmind_health", arguments: {} });
71
+ return parseToolJson(res.content?.[0]?.text ?? "{}");
72
+ }
73
+
74
+ /**
75
+ * Lädt ein Dokument hoch. Default-Pfad: Client rechnet die Embeddings
76
+ * lokal und schickt sie mit — der Server speichert nur noch, ohne eigene
77
+ * Berechnung. Skaliert deutlich besser.
78
+ *
79
+ * Wird KNOWMIND_EMBED_MODE=server gesetzt, geht der alte Pfad: Server
80
+ * rechnet selbst. Sinnvoll als Fallback, wenn der Client kein Modell
81
+ * laden kann (z. B. RAM-knapp).
82
+ */
83
+ export async function uploadDocument(title, content, opts = {}) {
84
+ const { apiUrl, token } = loadConfig();
85
+ if (!token) throw new Error("Kein Token konfiguriert.");
86
+
87
+ const mode = (process.env.KNOWMIND_EMBED_MODE || "client").toLowerCase();
88
+ let body;
89
+ if (mode === "client") {
90
+ try {
91
+ const { prepareChunks, embedBatch, MODEL } = await import("./local-embedding.js");
92
+ // prepareChunks zerlegt Text in Standard-Chunks UND extrahiert
93
+ // Preference-/Fact-/Update-Statements als Zusatz-Chunks mit type-Tag.
94
+ // Recall-Server boostet die getaggten Chunks für passende Queries.
95
+ const prepared = await prepareChunks(content);
96
+ const vectors = await embedBatch(prepared.map((c) => c.content), "passage");
97
+ body = {
98
+ title,
99
+ content,
100
+ chunks: prepared.map((c, i) => ({
101
+ content: c.content,
102
+ embedding: vectors[i],
103
+ ...(c.metadata ? { metadata: c.metadata } : {}),
104
+ })),
105
+ embeddingModel: MODEL,
106
+ };
107
+ } catch (err) {
108
+ process.stderr.write(
109
+ `[knowmind] lokales Embedding fehlgeschlagen, fallback auf Server: ${err.message}\n`,
110
+ );
111
+ body = { title, content };
112
+ }
113
+ } else {
114
+ body = { title, content };
115
+ }
116
+
117
+ // Upsert per documentId: kennt der Sync aus dem Manifest die Vorgaenger-
118
+ // documentId, geht sie als replaceDocumentId mit — der Server ersetzt damit
119
+ // genau diese Alt-Version, titelunabhaengig (verhindert Titel-Dubletten).
120
+ if (opts.replaceDocumentId) body.replaceDocumentId = opts.replaceDocumentId;
121
+
122
+ const r = await fetch(`${apiUrl}/api/documents`, {
123
+ method: "POST",
124
+ headers: { "content-type": "application/json", authorization: `Bearer ${token}` },
125
+ body: JSON.stringify(body),
126
+ });
127
+ const text = await r.text();
128
+ let data;
129
+ try {
130
+ data = text ? JSON.parse(text) : {};
131
+ } catch {
132
+ if (!r.ok) {
133
+ throw new Error(`HTTP ${r.status} ${r.statusText} — ${text.slice(0, 200)}`);
134
+ }
135
+ throw new Error(`HTTP ${r.status} lieferte ungültiges JSON: ${text.slice(0, 200)}`);
136
+ }
137
+ if (!r.ok) throw new Error(data.error ?? `HTTP ${r.status} ${r.statusText}`);
138
+ return data;
139
+ }
140
+
141
+ export async function listTools() {
142
+ return await rpc("tools/list", {});
143
+ }