knowmind 0.3.1 → 0.3.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/bin/knowmind.js CHANGED
@@ -1,360 +1,360 @@
1
- #!/usr/bin/env node
2
- /**
3
- * Knowmind CLI Entry-Point.
4
- *
5
- * Verfügbare Befehle:
6
- * knowmind login [--token kmt_…] — API-Token speichern
7
- * knowmind config — aktuelle Config anzeigen
8
- * knowmind search "Frage" [-k 5] — Recall
9
- * knowmind upload <file> [--title] — Dokument-Ingestion
10
- * knowmind stats — Korpus-Statistik
11
- * knowmind health — Service-Health
12
- * knowmind mcp — Stdio-MCP-Server
13
- */
14
- import { readFileSync } from "node:fs";
15
- import { basename } from "node:path";
16
- import { stdin as input } from "node:process";
17
- import {
18
- recall,
19
- uploadDocument,
20
- stats,
21
- health,
22
- } from "../src/client.js";
23
- import { loadConfig, saveConfig, configPath, VERSION } from "../src/config.js";
24
- import { runStdioServer } from "../src/mcp-stdio.js";
25
- import { syncDirectory } from "../src/sync.js";
26
- import { runInit } from "../src/init.js";
27
- import { runInstall } from "../src/install.js";
28
- import { renderLine, renderFull, probe } from "../src/status.js";
29
-
30
- const args = process.argv.slice(2);
31
- const cmd = args[0];
32
-
33
- function parseFlag(name, fallback) {
34
- const i = args.indexOf(name);
35
- if (i < 0) return fallback;
36
- return args[i + 1] ?? fallback;
37
- }
38
-
39
- async function readStdin() {
40
- return await new Promise((resolve) => {
41
- let data = "";
42
- input.setEncoding("utf-8");
43
- input.on("data", (c) => (data += c));
44
- input.on("end", () => resolve(data));
45
- });
46
- }
47
-
48
- function help() {
49
- console.log(`
50
- Knowmind ${VERSION} — Das Gedächtnis für Ihre KI
51
-
52
- Befehle:
53
- knowmind login [--token kmt_TOKEN] [--api https://knowmind.de]
54
- Token speichern
55
- knowmind init [--client claude-code|cursor|auto] [--token kmt_TOKEN] [--api URL] [--dry-run]
56
- Automatische Gedächtnis-Pflege im KI-Client einrichten
57
- (Hooks/Regeln + Memory-First-Block). Idempotent.
58
- --token/--api legen die Config gleich mit an.
59
- knowmind config Aktuelle Konfiguration anzeigen
60
- knowmind search "Frage" [-k 5] [--hops 2]
61
- Hybrid-Recall gegen den Tenant-Korpus
62
- knowmind upload <file> [--title "..."]
63
- Markdown-/Text-Datei indexieren (stdin: knowmind upload -)
64
- knowmind sync <dir> [--ext .md,.txt] [--verbose] [--title-from-content]
65
- Ordner mit dem Korpus abgleichen. Idempotent über
66
- Content-Hash, Manifest in <dir>/.knowmind-manifest.json.
67
- knowmind stats Memory- und Edge-Counter des Tenants
68
- knowmind health Health-Check der Plattform
69
- knowmind status [--line]
70
- Lebenszeichen des Gedächtnisses. Ohne Flag: Report.
71
- --line: einzeilige Statusline (grüne HDD-LED, flackert
72
- bei Aktivität, rot bei Ausfall) — für die Statusline
73
- eines KI-Werkzeugs, z. B. Claude Code.
74
- knowmind mcp Stdio-MCP-Server für lokale AI-Clients
75
- knowmind install <ide> [--project] [--print] [--token T] [--api URL]
76
- knowmind als MCP-Server in eine IDE eintragen
77
- (cursor, vscode, windsurf, antigravity, zed, jetbrains,
78
- claude-code, claude-desktop, all). 'install list' zeigt alle.
79
-
80
- ENV-Override:
81
- KNOWMIND_API_URL z. B. https://knowmind.de
82
- KNOWMIND_TOKEN Bearer-Token (überschreibt Config-File)
83
- `);
84
- }
85
-
86
- /**
87
- * Klarer Hinweis, wo man ein kostenloses Konto + Token bekommt. Wird gezeigt,
88
- * sobald (noch) kein gültiger Token vorliegt — der häufigste Stolperstein für
89
- * Erstnutzer. API/CLI sind im kostenlosen Tarif enthalten (bis 2.500 Memories).
90
- * apiUrl wird dynamisch bezogen (--api / KNOWMIND_API_URL / Default), nie geraten.
91
- */
92
- function printRegisterHint(api) {
93
- const base = api || process.env.KNOWMIND_API_URL || "https://knowmind.de";
94
- console.log(
95
- "\nknowmind braucht ein kostenloses Konto + einen API-Token:\n" +
96
- ` 1. Konto anlegen: ${base}/signin?mode=register\n` +
97
- ` 2. Token erzeugen: ${base}/dashboard/tokens (Dashboard -> API-Tokens -> Token erstellen)\n` +
98
- " 3. Einloggen: knowmind login --token kmt_...\n\n" +
99
- "API und CLI sind im kostenlosen Tarif enthalten (bis 2.500 Erinnerungen).\n",
100
- );
101
- }
102
-
103
- /** Ist ein Token konfiguriert (ENV oder Config-File)? */
104
- function hasToken() {
105
- return Boolean(process.env.KNOWMIND_TOKEN || loadConfig().token);
106
- }
107
-
108
- /**
109
- * Geführter Abschluss nach `install`/`init`: Ohne Token bleibt die Eintragung
110
- * wirkungslos (tote MCP-Konfig) — der häufigste Stolperstein. Bei vorhandenem
111
- * Token: kurze Bestätigung. Sonst: deutlicher Schluss-Schritt mit Anleitung.
112
- */
113
- function finishOnboardingHint() {
114
- if (hasToken()) {
115
- console.log("\n✓ Token gefunden — knowmind ist startklar, sobald der Client neu lädt.");
116
- return;
117
- }
118
- console.log(
119
- "\n⚠ LETZTER SCHRITT: Ohne API-Token ist die Eintragung noch wirkungslos (keine Verbindung).",
120
- );
121
- printRegisterHint(parseFlag("--api", null));
122
- }
123
-
124
- async function runLogin() {
125
- let token = parseFlag("--token", null);
126
- const api = parseFlag("--api", null);
127
- if (!token) {
128
- // Kein Token übergeben -> erst zeigen, wo man ihn herbekommt, dann fragen.
129
- printRegisterHint(api);
130
- // Interaktiv von stdin lesen
131
- process.stdout.write("API-Token (kmt_…): ");
132
- const line = await new Promise((resolve) => {
133
- input.once("data", (d) => resolve(d.toString().trim()));
134
- });
135
- token = line;
136
- }
137
- if (!token || !token.startsWith("kmt_")) {
138
- printRegisterHint(api);
139
- throw new Error("Token muss mit kmt_ beginnen.");
140
- }
141
-
142
- // Vor dem Speichern: Token gegen Server verifizieren. Sonst wäre jeder
143
- // Phantasie-String akzeptiert und alle späteren Aufrufe scheitern erst
144
- // beim ersten echten Call — das ist verwirrend.
145
- const apiUrl = api || process.env.KNOWMIND_API_URL || loadConfig().apiUrl;
146
- process.stdout.write("Token wird gegen Server verifiziert … ");
147
- const r = await fetch(`${apiUrl}/api/mcp/v1`, {
148
- method: "POST",
149
- headers: { "content-type": "application/json", authorization: `Bearer ${token}` },
150
- body: JSON.stringify({
151
- jsonrpc: "2.0",
152
- id: 1,
153
- method: "tools/call",
154
- params: { name: "knowmind_health", arguments: {} },
155
- }),
156
- }).catch((e) => ({ ok: false, _netError: e.message }));
157
- if (r._netError) {
158
- process.stdout.write("FEHLER\n");
159
- throw new Error(`Server nicht erreichbar (${apiUrl}): ${r._netError}`);
160
- }
161
- const data = await r.json().catch(() => ({}));
162
- if (!r.ok || data.error) {
163
- process.stdout.write("ABGELEHNT\n");
164
- const code = data.error?.code ?? r.status;
165
- const msg = data.error?.message ?? `HTTP ${r.status}`;
166
- printRegisterHint(api);
167
- throw new Error(`Token ungültig: ${code} — ${msg}`);
168
- }
169
- process.stdout.write("ok\n");
170
- const where = saveConfig({ token, ...(api ? { apiUrl: api } : {}) });
171
- console.log(`Token gespeichert in ${where}.`);
172
- }
173
-
174
- async function runSearch() {
175
- const query = args.slice(1).filter((a) => !a.startsWith("-")).join(" ");
176
- if (!query) throw new Error('Usage: knowmind search "Ihre Frage"');
177
- const k = Number(parseFlag("-k", parseFlag("--k", 5)));
178
- const hops = Number(parseFlag("--hops", 2));
179
- const result = await recall(query, { k, hops });
180
- if (!result?.hits?.length) {
181
- console.log("Keine Treffer.");
182
- return;
183
- }
184
- for (const [i, hit] of result.hits.entries()) {
185
- const src = hit.metadata?.source_id ?? hit.chunk_id;
186
- const name = hit.metadata?.name ?? src;
187
- console.log(`\n#${i + 1} ${name} (score ${hit.score.toFixed(3)})`);
188
- console.log(" " + hit.content.slice(0, 280).replace(/\n/g, "\n "));
189
- }
190
- console.log(`\n${result.hits.length} Treffer in ${result.latency_ms} ms.`);
191
- }
192
-
193
- async function runUpload() {
194
- const path = args[1];
195
- if (!path) throw new Error("Usage: knowmind upload <file> (oder `-` für stdin)");
196
- let content;
197
- let title = parseFlag("--title", null);
198
- if (path === "-") {
199
- content = await readStdin();
200
- title = title ?? "stdin";
201
- } else {
202
- content = readFileSync(path, "utf-8");
203
- title = title ?? basename(path);
204
- }
205
- const data = await uploadDocument(title, content);
206
- if (data.unchanged || data.duplicate) {
207
- console.log(`Unverändert/Duplikat: Inhalt liegt bereits indexiert vor (Doc ${data.id ?? "?"}).`);
208
- } else {
209
- console.log(`Indexiert: ${data.chunksWritten} Chunks (Provider ${data.embeddingProvider}).`);
210
- }
211
- }
212
-
213
- async function runSync() {
214
- const dir = args[1];
215
- if (!dir) throw new Error("Usage: knowmind sync <directory>");
216
- const extFlag = parseFlag("--ext", null);
217
- const options = {
218
- extensions: extFlag ? extFlag.split(",").map((e) => (e.startsWith(".") ? e : `.${e}`)) : undefined,
219
- verbose: args.includes("--verbose"),
220
- titleFromContent: args.includes("--title-from-content"),
221
- };
222
- const result = await syncDirectory(dir, options);
223
- if (result.failed > 0) process.exitCode = 3;
224
- }
225
-
226
-
227
- async function runStats() {
228
- console.log(JSON.stringify(await stats(), null, 2));
229
- }
230
-
231
- async function runHealth() {
232
- console.log(JSON.stringify(await health(), null, 2));
233
- }
234
-
235
- async function runConfig() {
236
- const c = loadConfig();
237
- console.log(`Config-Datei: ${configPath()}`);
238
- console.log(`API-URL: ${c.apiUrl}`);
239
- console.log(`Token: ${c.token ? c.token.slice(0, 12) + "…" : "(keiner)"}`);
240
- }
241
-
242
- async function runStatus() {
243
- // --probe: interner Hintergrund-Refresh der Status-Caches (nicht blockierend
244
- // für die Statusline). --line: einzeilige, gefärbte Ausgabe für die Statusline
245
- // eines KI-Werkzeugs. Ohne Flag: menschenlesbarer Mehrzeilen-Report.
246
- if (args.includes("--probe")) {
247
- await probe();
248
- return;
249
- }
250
- if (args.includes("--line")) {
251
- // Claude Code reicht der Statusline ein JSON per stdin (u. a. session_id).
252
- // Non-blocking mit kurzem Timeout lesen — bei manuellem Aufruf ohne stdin
253
- // darf nichts hängen. session_id ergibt den Sitzungs-Recall-Zähler.
254
- let sessionId = "";
255
- try {
256
- const raw = await Promise.race([
257
- readStdin(),
258
- new Promise((r) => setTimeout(() => r(""), 80)),
259
- ]);
260
- if (raw && raw.trim().startsWith("{")) {
261
- const d = JSON.parse(raw);
262
- sessionId = d.session_id || d.sessionId || "";
263
- }
264
- } catch {
265
- /* kein/kaputtes stdin — ohne Session weiter */
266
- }
267
- process.stdout.write(renderLine(sessionId));
268
- return;
269
- }
270
- console.log(await renderFull());
271
- }
272
-
273
- async function runInitCmd() {
274
- const client = parseFlag("--client", "auto");
275
- const dryRun = args.includes("--dry-run");
276
- // Konsistenz zu `install`: --token/--api direkt verarbeiten und in der Config
277
- // ablegen, damit die erzeugten Hooks (sie lesen Token/URL aus ~/.knowmind/
278
- // config.json bzw. ENV) sofort funktionieren statt still ins Leere zu laufen.
279
- const token = parseFlag("--token", null);
280
- const api = parseFlag("--api", null);
281
- if ((token || api) && !dryRun) {
282
- if (token && !token.startsWith("kmt_")) throw new Error("Token muss mit kmt_ beginnen.");
283
- const where = saveConfig({ ...(token ? { token } : {}), ...(api ? { apiUrl: api } : {}) });
284
- if (token) console.log(`Token gespeichert in ${where}.`);
285
- }
286
- console.log(await runInit({ client, dryRun }));
287
- if (!dryRun) finishOnboardingHint();
288
- }
289
-
290
- async function runInstallCmd() {
291
- const ideKey = args[1] && !args[1].startsWith("-") ? args[1] : null;
292
- runInstall({
293
- ideKey,
294
- project: args.includes("--project"),
295
- dryRun: args.includes("--dry-run"),
296
- printOnly: args.includes("--print"),
297
- apiUrl: parseFlag("--api", null),
298
- literalToken: parseFlag("--token", null),
299
- });
300
- // Nach echter Eintragung (nicht bei list/--print/--dry-run) zum Token führen.
301
- if (ideKey && ideKey !== "list" && !args.includes("--print") && !args.includes("--dry-run")) {
302
- finishOnboardingHint();
303
- }
304
- }
305
-
306
- // Wichtig: `process.exit(N)` reißt offene Sockets/fetch-Verbindungen mit
307
- // rein und triggert auf Windows/Node 22 die libuv-Assertion
308
- // `!(handle->flags & UV_HANDLE_CLOSING)`. Stattdessen `exitCode` setzen
309
- // und sauber zurückkehren — Node beendet sich von selbst, sobald keine
310
- // offenen Handles mehr da sind.
311
- try {
312
- switch (cmd) {
313
- case "login":
314
- await runLogin();
315
- break;
316
- case "config":
317
- await runConfig();
318
- break;
319
- case "search":
320
- await runSearch();
321
- break;
322
- case "upload":
323
- await runUpload();
324
- break;
325
- case "sync":
326
- await runSync();
327
- break;
328
- case "stats":
329
- await runStats();
330
- break;
331
- case "health":
332
- await runHealth();
333
- break;
334
- case "status":
335
- await runStatus();
336
- break;
337
- case "mcp":
338
- await runStdioServer();
339
- break;
340
- case "install":
341
- await runInstallCmd();
342
- break;
343
- case "init":
344
- await runInitCmd();
345
- break;
346
- case "--help":
347
- case "-h":
348
- case "help":
349
- case undefined:
350
- help();
351
- break;
352
- default:
353
- console.error(`Unbekannter Befehl: ${cmd}`);
354
- help();
355
- process.exitCode = 1;
356
- }
357
- } catch (e) {
358
- console.error(`Fehler: ${e.message}`);
359
- process.exitCode = 2;
360
- }
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Knowmind CLI Entry-Point.
4
+ *
5
+ * Verfügbare Befehle:
6
+ * knowmind login [--token kmt_…] — API-Token speichern
7
+ * knowmind config — aktuelle Config anzeigen
8
+ * knowmind search "Frage" [-k 5] — Recall
9
+ * knowmind upload <file> [--title] — Dokument-Ingestion
10
+ * knowmind stats — Korpus-Statistik
11
+ * knowmind health — Service-Health
12
+ * knowmind mcp — Stdio-MCP-Server
13
+ */
14
+ import { readFileSync } from "node:fs";
15
+ import { basename } from "node:path";
16
+ import { stdin as input } from "node:process";
17
+ import {
18
+ recall,
19
+ uploadDocument,
20
+ stats,
21
+ health,
22
+ } from "../src/client.js";
23
+ import { loadConfig, saveConfig, configPath, VERSION } from "../src/config.js";
24
+ import { runStdioServer } from "../src/mcp-stdio.js";
25
+ import { syncDirectory } from "../src/sync.js";
26
+ import { runInit } from "../src/init.js";
27
+ import { runInstall } from "../src/install.js";
28
+ import { renderLine, renderFull, probe } from "../src/status.js";
29
+
30
+ const args = process.argv.slice(2);
31
+ const cmd = args[0];
32
+
33
+ function parseFlag(name, fallback) {
34
+ const i = args.indexOf(name);
35
+ if (i < 0) return fallback;
36
+ return args[i + 1] ?? fallback;
37
+ }
38
+
39
+ async function readStdin() {
40
+ return await new Promise((resolve) => {
41
+ let data = "";
42
+ input.setEncoding("utf-8");
43
+ input.on("data", (c) => (data += c));
44
+ input.on("end", () => resolve(data));
45
+ });
46
+ }
47
+
48
+ function help() {
49
+ console.log(`
50
+ Knowmind ${VERSION} — Das Gedächtnis für Ihre KI
51
+
52
+ Befehle:
53
+ knowmind login [--token kmt_TOKEN] [--api https://knowmind.de]
54
+ Token speichern
55
+ knowmind init [--client claude-code|cursor|auto] [--token kmt_TOKEN] [--api URL] [--dry-run]
56
+ Automatische Gedächtnis-Pflege im KI-Client einrichten
57
+ (Hooks/Regeln + Memory-First-Block). Idempotent.
58
+ --token/--api legen die Config gleich mit an.
59
+ knowmind config Aktuelle Konfiguration anzeigen
60
+ knowmind search "Frage" [-k 5] [--hops 2]
61
+ Hybrid-Recall gegen den Tenant-Korpus
62
+ knowmind upload <file> [--title "..."]
63
+ Markdown-/Text-Datei indexieren (stdin: knowmind upload -)
64
+ knowmind sync <dir> [--ext .md,.txt] [--verbose] [--title-from-content]
65
+ Ordner mit dem Korpus abgleichen. Idempotent über
66
+ Content-Hash, Manifest in <dir>/.knowmind-manifest.json.
67
+ knowmind stats Memory- und Edge-Counter des Tenants
68
+ knowmind health Health-Check der Plattform
69
+ knowmind status [--line]
70
+ Lebenszeichen des Gedächtnisses. Ohne Flag: Report.
71
+ --line: einzeilige Statusline (grüne HDD-LED, flackert
72
+ bei Aktivität, rot bei Ausfall) — für die Statusline
73
+ eines KI-Werkzeugs, z. B. Claude Code.
74
+ knowmind mcp Stdio-MCP-Server für lokale AI-Clients
75
+ knowmind install <ide> [--project] [--print] [--token T] [--api URL]
76
+ knowmind als MCP-Server in eine IDE eintragen
77
+ (cursor, vscode, windsurf, antigravity, zed, jetbrains, gemini,
78
+ codex, claude-code, claude-desktop, all). 'install list' zeigt alle.
79
+
80
+ ENV-Override:
81
+ KNOWMIND_API_URL z. B. https://knowmind.de
82
+ KNOWMIND_TOKEN Bearer-Token (überschreibt Config-File)
83
+ `);
84
+ }
85
+
86
+ /**
87
+ * Klarer Hinweis, wo man ein kostenloses Konto + Token bekommt. Wird gezeigt,
88
+ * sobald (noch) kein gültiger Token vorliegt — der häufigste Stolperstein für
89
+ * Erstnutzer. API/CLI sind im kostenlosen Tarif enthalten (bis 2.500 Memories).
90
+ * apiUrl wird dynamisch bezogen (--api / KNOWMIND_API_URL / Default), nie geraten.
91
+ */
92
+ function printRegisterHint(api) {
93
+ const base = api || process.env.KNOWMIND_API_URL || "https://knowmind.de";
94
+ console.log(
95
+ "\nknowmind braucht ein kostenloses Konto + einen API-Token:\n" +
96
+ ` 1. Konto anlegen: ${base}/signin?mode=register\n` +
97
+ ` 2. Token erzeugen: ${base}/dashboard/tokens (Dashboard -> API-Tokens -> Token erstellen)\n` +
98
+ " 3. Einloggen: knowmind login --token kmt_...\n\n" +
99
+ "API und CLI sind im kostenlosen Tarif enthalten (bis 2.500 Erinnerungen).\n",
100
+ );
101
+ }
102
+
103
+ /** Ist ein Token konfiguriert (ENV oder Config-File)? */
104
+ function hasToken() {
105
+ return Boolean(process.env.KNOWMIND_TOKEN || loadConfig().token);
106
+ }
107
+
108
+ /**
109
+ * Geführter Abschluss nach `install`/`init`: Ohne Token bleibt die Eintragung
110
+ * wirkungslos (tote MCP-Konfig) — der häufigste Stolperstein. Bei vorhandenem
111
+ * Token: kurze Bestätigung. Sonst: deutlicher Schluss-Schritt mit Anleitung.
112
+ */
113
+ function finishOnboardingHint() {
114
+ if (hasToken()) {
115
+ console.log("\n✓ Token gefunden — knowmind ist startklar, sobald der Client neu lädt.");
116
+ return;
117
+ }
118
+ console.log(
119
+ "\n⚠ LETZTER SCHRITT: Ohne API-Token ist die Eintragung noch wirkungslos (keine Verbindung).",
120
+ );
121
+ printRegisterHint(parseFlag("--api", null));
122
+ }
123
+
124
+ async function runLogin() {
125
+ let token = parseFlag("--token", null);
126
+ const api = parseFlag("--api", null);
127
+ if (!token) {
128
+ // Kein Token übergeben -> erst zeigen, wo man ihn herbekommt, dann fragen.
129
+ printRegisterHint(api);
130
+ // Interaktiv von stdin lesen
131
+ process.stdout.write("API-Token (kmt_…): ");
132
+ const line = await new Promise((resolve) => {
133
+ input.once("data", (d) => resolve(d.toString().trim()));
134
+ });
135
+ token = line;
136
+ }
137
+ if (!token || !token.startsWith("kmt_")) {
138
+ printRegisterHint(api);
139
+ throw new Error("Token muss mit kmt_ beginnen.");
140
+ }
141
+
142
+ // Vor dem Speichern: Token gegen Server verifizieren. Sonst wäre jeder
143
+ // Phantasie-String akzeptiert und alle späteren Aufrufe scheitern erst
144
+ // beim ersten echten Call — das ist verwirrend.
145
+ const apiUrl = api || process.env.KNOWMIND_API_URL || loadConfig().apiUrl;
146
+ process.stdout.write("Token wird gegen Server verifiziert … ");
147
+ const r = await fetch(`${apiUrl}/api/mcp/v1`, {
148
+ method: "POST",
149
+ headers: { "content-type": "application/json", authorization: `Bearer ${token}` },
150
+ body: JSON.stringify({
151
+ jsonrpc: "2.0",
152
+ id: 1,
153
+ method: "tools/call",
154
+ params: { name: "knowmind_health", arguments: {} },
155
+ }),
156
+ }).catch((e) => ({ ok: false, _netError: e.message }));
157
+ if (r._netError) {
158
+ process.stdout.write("FEHLER\n");
159
+ throw new Error(`Server nicht erreichbar (${apiUrl}): ${r._netError}`);
160
+ }
161
+ const data = await r.json().catch(() => ({}));
162
+ if (!r.ok || data.error) {
163
+ process.stdout.write("ABGELEHNT\n");
164
+ const code = data.error?.code ?? r.status;
165
+ const msg = data.error?.message ?? `HTTP ${r.status}`;
166
+ printRegisterHint(api);
167
+ throw new Error(`Token ungültig: ${code} — ${msg}`);
168
+ }
169
+ process.stdout.write("ok\n");
170
+ const where = saveConfig({ token, ...(api ? { apiUrl: api } : {}) });
171
+ console.log(`Token gespeichert in ${where}.`);
172
+ }
173
+
174
+ async function runSearch() {
175
+ const query = args.slice(1).filter((a) => !a.startsWith("-")).join(" ");
176
+ if (!query) throw new Error('Usage: knowmind search "Ihre Frage"');
177
+ const k = Number(parseFlag("-k", parseFlag("--k", 5)));
178
+ const hops = Number(parseFlag("--hops", 2));
179
+ const result = await recall(query, { k, hops });
180
+ if (!result?.hits?.length) {
181
+ console.log("Keine Treffer.");
182
+ return;
183
+ }
184
+ for (const [i, hit] of result.hits.entries()) {
185
+ const src = hit.metadata?.source_id ?? hit.chunk_id;
186
+ const name = hit.metadata?.name ?? src;
187
+ console.log(`\n#${i + 1} ${name} (score ${hit.score.toFixed(3)})`);
188
+ console.log(" " + hit.content.slice(0, 280).replace(/\n/g, "\n "));
189
+ }
190
+ console.log(`\n${result.hits.length} Treffer in ${result.latency_ms} ms.`);
191
+ }
192
+
193
+ async function runUpload() {
194
+ const path = args[1];
195
+ if (!path) throw new Error("Usage: knowmind upload <file> (oder `-` für stdin)");
196
+ let content;
197
+ let title = parseFlag("--title", null);
198
+ if (path === "-") {
199
+ content = await readStdin();
200
+ title = title ?? "stdin";
201
+ } else {
202
+ content = readFileSync(path, "utf-8");
203
+ title = title ?? basename(path);
204
+ }
205
+ const data = await uploadDocument(title, content);
206
+ if (data.unchanged || data.duplicate) {
207
+ console.log(`Unverändert/Duplikat: Inhalt liegt bereits indexiert vor (Doc ${data.id ?? "?"}).`);
208
+ } else {
209
+ console.log(`Indexiert: ${data.chunksWritten} Chunks (Provider ${data.embeddingProvider}).`);
210
+ }
211
+ }
212
+
213
+ async function runSync() {
214
+ const dir = args[1];
215
+ if (!dir) throw new Error("Usage: knowmind sync <directory>");
216
+ const extFlag = parseFlag("--ext", null);
217
+ const options = {
218
+ extensions: extFlag ? extFlag.split(",").map((e) => (e.startsWith(".") ? e : `.${e}`)) : undefined,
219
+ verbose: args.includes("--verbose"),
220
+ titleFromContent: args.includes("--title-from-content"),
221
+ };
222
+ const result = await syncDirectory(dir, options);
223
+ if (result.failed > 0) process.exitCode = 3;
224
+ }
225
+
226
+
227
+ async function runStats() {
228
+ console.log(JSON.stringify(await stats(), null, 2));
229
+ }
230
+
231
+ async function runHealth() {
232
+ console.log(JSON.stringify(await health(), null, 2));
233
+ }
234
+
235
+ async function runConfig() {
236
+ const c = loadConfig();
237
+ console.log(`Config-Datei: ${configPath()}`);
238
+ console.log(`API-URL: ${c.apiUrl}`);
239
+ console.log(`Token: ${c.token ? c.token.slice(0, 12) + "…" : "(keiner)"}`);
240
+ }
241
+
242
+ async function runStatus() {
243
+ // --probe: interner Hintergrund-Refresh der Status-Caches (nicht blockierend
244
+ // für die Statusline). --line: einzeilige, gefärbte Ausgabe für die Statusline
245
+ // eines KI-Werkzeugs. Ohne Flag: menschenlesbarer Mehrzeilen-Report.
246
+ if (args.includes("--probe")) {
247
+ await probe();
248
+ return;
249
+ }
250
+ if (args.includes("--line")) {
251
+ // Claude Code reicht der Statusline ein JSON per stdin (u. a. session_id).
252
+ // Non-blocking mit kurzem Timeout lesen — bei manuellem Aufruf ohne stdin
253
+ // darf nichts hängen. session_id ergibt den Sitzungs-Recall-Zähler.
254
+ let sessionId = "";
255
+ try {
256
+ const raw = await Promise.race([
257
+ readStdin(),
258
+ new Promise((r) => setTimeout(() => r(""), 80)),
259
+ ]);
260
+ if (raw && raw.trim().startsWith("{")) {
261
+ const d = JSON.parse(raw);
262
+ sessionId = d.session_id || d.sessionId || "";
263
+ }
264
+ } catch {
265
+ /* kein/kaputtes stdin — ohne Session weiter */
266
+ }
267
+ process.stdout.write(renderLine(sessionId));
268
+ return;
269
+ }
270
+ console.log(await renderFull());
271
+ }
272
+
273
+ async function runInitCmd() {
274
+ const client = parseFlag("--client", "auto");
275
+ const dryRun = args.includes("--dry-run");
276
+ // Konsistenz zu `install`: --token/--api direkt verarbeiten und in der Config
277
+ // ablegen, damit die erzeugten Hooks (sie lesen Token/URL aus ~/.knowmind/
278
+ // config.json bzw. ENV) sofort funktionieren statt still ins Leere zu laufen.
279
+ const token = parseFlag("--token", null);
280
+ const api = parseFlag("--api", null);
281
+ if ((token || api) && !dryRun) {
282
+ if (token && !token.startsWith("kmt_")) throw new Error("Token muss mit kmt_ beginnen.");
283
+ const where = saveConfig({ ...(token ? { token } : {}), ...(api ? { apiUrl: api } : {}) });
284
+ if (token) console.log(`Token gespeichert in ${where}.`);
285
+ }
286
+ console.log(await runInit({ client, dryRun }));
287
+ if (!dryRun) finishOnboardingHint();
288
+ }
289
+
290
+ async function runInstallCmd() {
291
+ const ideKey = args[1] && !args[1].startsWith("-") ? args[1] : null;
292
+ runInstall({
293
+ ideKey,
294
+ project: args.includes("--project"),
295
+ dryRun: args.includes("--dry-run"),
296
+ printOnly: args.includes("--print"),
297
+ apiUrl: parseFlag("--api", null),
298
+ literalToken: parseFlag("--token", null),
299
+ });
300
+ // Nach echter Eintragung (nicht bei list/--print/--dry-run) zum Token führen.
301
+ if (ideKey && ideKey !== "list" && !args.includes("--print") && !args.includes("--dry-run")) {
302
+ finishOnboardingHint();
303
+ }
304
+ }
305
+
306
+ // Wichtig: `process.exit(N)` reißt offene Sockets/fetch-Verbindungen mit
307
+ // rein und triggert auf Windows/Node 22 die libuv-Assertion
308
+ // `!(handle->flags & UV_HANDLE_CLOSING)`. Stattdessen `exitCode` setzen
309
+ // und sauber zurückkehren — Node beendet sich von selbst, sobald keine
310
+ // offenen Handles mehr da sind.
311
+ try {
312
+ switch (cmd) {
313
+ case "login":
314
+ await runLogin();
315
+ break;
316
+ case "config":
317
+ await runConfig();
318
+ break;
319
+ case "search":
320
+ await runSearch();
321
+ break;
322
+ case "upload":
323
+ await runUpload();
324
+ break;
325
+ case "sync":
326
+ await runSync();
327
+ break;
328
+ case "stats":
329
+ await runStats();
330
+ break;
331
+ case "health":
332
+ await runHealth();
333
+ break;
334
+ case "status":
335
+ await runStatus();
336
+ break;
337
+ case "mcp":
338
+ await runStdioServer();
339
+ break;
340
+ case "install":
341
+ await runInstallCmd();
342
+ break;
343
+ case "init":
344
+ await runInitCmd();
345
+ break;
346
+ case "--help":
347
+ case "-h":
348
+ case "help":
349
+ case undefined:
350
+ help();
351
+ break;
352
+ default:
353
+ console.error(`Unbekannter Befehl: ${cmd}`);
354
+ help();
355
+ process.exitCode = 1;
356
+ }
357
+ } catch (e) {
358
+ console.error(`Fehler: ${e.message}`);
359
+ process.exitCode = 2;
360
+ }