@memoryrouter/cli 0.1.0

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.
Files changed (2) hide show
  1. package/dist/index.js +484 -0
  2. package/package.json +41 -0
package/dist/index.js ADDED
@@ -0,0 +1,484 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/index.ts
4
+ import { Command } from "commander";
5
+
6
+ // src/config.ts
7
+ import fs from "fs";
8
+ import path from "path";
9
+ import os from "os";
10
+ var CONFIG_DIR = path.join(os.homedir(), ".memoryrouter");
11
+ var CONFIG_FILE = path.join(CONFIG_DIR, "config.json");
12
+ function loadConfig() {
13
+ try {
14
+ if (!fs.existsSync(CONFIG_FILE)) return null;
15
+ const raw = fs.readFileSync(CONFIG_FILE, "utf-8");
16
+ return JSON.parse(raw);
17
+ } catch {
18
+ return null;
19
+ }
20
+ }
21
+ function saveConfig(config) {
22
+ if (!fs.existsSync(CONFIG_DIR)) {
23
+ fs.mkdirSync(CONFIG_DIR, { recursive: true });
24
+ }
25
+ fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2) + "\n");
26
+ }
27
+ function requireConfig() {
28
+ const config = loadConfig();
29
+ if (!config?.key) {
30
+ console.error("Not authenticated. Run: memoryrouter auth <your-memory-key>");
31
+ process.exit(1);
32
+ }
33
+ return config;
34
+ }
35
+ function getEndpoint(config) {
36
+ return (config.endpoint ?? "https://api.memoryrouter.ai/v1").replace(/\/v1$/, "");
37
+ }
38
+ function maskKey(key) {
39
+ if (key.length <= 12) return key;
40
+ return `${key.slice(0, 6)}...${key.slice(-3)}`;
41
+ }
42
+
43
+ // src/api.ts
44
+ var MAX_RETRIES = 5;
45
+ var INITIAL_BACKOFF_MS = 2e3;
46
+ var MAX_BACKOFF_MS = 3e4;
47
+ function sleep(ms) {
48
+ return new Promise((resolve) => setTimeout(resolve, ms));
49
+ }
50
+ async function fetchWithRetry(url, options, context) {
51
+ let lastError = null;
52
+ let backoff = INITIAL_BACKOFF_MS;
53
+ for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
54
+ try {
55
+ const response = await fetch(url, options);
56
+ if (response.ok) return response;
57
+ if (response.status === 429 || response.status >= 500) {
58
+ const retryAfter = response.headers.get("Retry-After");
59
+ const waitMs = retryAfter ? parseInt(retryAfter, 10) * 1e3 : backoff;
60
+ const actualWait = Math.min(waitMs, MAX_BACKOFF_MS);
61
+ if (attempt < MAX_RETRIES) {
62
+ process.stdout.write(`
63
+ \u23F3 ${context}: ${response.status} \u2014 retrying in ${Math.round(actualWait / 1e3)}s (${attempt}/${MAX_RETRIES})...`);
64
+ await sleep(actualWait);
65
+ backoff = Math.min(backoff * 2, MAX_BACKOFF_MS);
66
+ continue;
67
+ }
68
+ }
69
+ const errorText = await response.text();
70
+ throw new Error(`HTTP ${response.status}: ${errorText}`);
71
+ } catch (err) {
72
+ lastError = err instanceof Error ? err : new Error(String(err));
73
+ if (attempt < MAX_RETRIES && (lastError.message.includes("fetch failed") || lastError.message.includes("ECONNRESET") || lastError.message.includes("ETIMEDOUT"))) {
74
+ process.stdout.write(`
75
+ \u23F3 ${context}: Network error \u2014 retrying in ${Math.round(backoff / 1e3)}s (${attempt}/${MAX_RETRIES})...`);
76
+ await sleep(backoff);
77
+ backoff = Math.min(backoff * 2, MAX_BACKOFF_MS);
78
+ continue;
79
+ }
80
+ throw lastError;
81
+ }
82
+ }
83
+ throw lastError ?? new Error("Max retries exceeded");
84
+ }
85
+ async function fetchStats(key, baseUrl) {
86
+ try {
87
+ const res = await fetch(`${baseUrl}/v1/memory/stats`, {
88
+ headers: { Authorization: `Bearer ${key}` }
89
+ });
90
+ if (!res.ok) return null;
91
+ const data = await res.json();
92
+ return {
93
+ memories: data.totalVectors ?? 0,
94
+ tokens: data.totalTokens ?? 0,
95
+ sessions: data.sessions ?? 0
96
+ };
97
+ } catch {
98
+ return null;
99
+ }
100
+ }
101
+ async function validateKey(key, baseUrl) {
102
+ try {
103
+ const res = await fetch(`${baseUrl}/v1/memory/stats`, {
104
+ headers: { Authorization: `Bearer ${key}` }
105
+ });
106
+ return res.ok;
107
+ } catch {
108
+ return false;
109
+ }
110
+ }
111
+ async function deleteVault(key, baseUrl, sessionId) {
112
+ const headers = { Authorization: `Bearer ${key}` };
113
+ if (sessionId) headers["X-Session-ID"] = sessionId;
114
+ const res = await fetch(`${baseUrl}/v1/memory`, {
115
+ method: "DELETE",
116
+ headers
117
+ });
118
+ if (!res.ok) {
119
+ const errorText = await res.text();
120
+ return { success: false, message: `${res.status}: ${errorText}` };
121
+ }
122
+ const result = await res.json();
123
+ return { success: true, message: result.message ?? result.status ?? "Vault cleared" };
124
+ }
125
+
126
+ // src/upload.ts
127
+ import fs2 from "fs";
128
+ import fsp from "fs/promises";
129
+ import path2 from "path";
130
+ var SUPPORTED_EXTENSIONS = /* @__PURE__ */ new Set([
131
+ ".md",
132
+ ".txt",
133
+ ".rst",
134
+ // docs
135
+ ".ts",
136
+ ".js",
137
+ ".py",
138
+ ".go",
139
+ // code
140
+ ".json",
141
+ ".yaml",
142
+ ".yml",
143
+ // config
144
+ ".csv",
145
+ ".tsv",
146
+ // data
147
+ ".html",
148
+ ".xml",
149
+ // markup
150
+ ".sh",
151
+ ".bash",
152
+ ".zsh",
153
+ // scripts
154
+ ".toml",
155
+ ".ini",
156
+ ".cfg",
157
+ // config
158
+ ".sql",
159
+ // queries
160
+ ".r",
161
+ ".jl",
162
+ ".rb",
163
+ ".java",
164
+ // more code
165
+ ".c",
166
+ ".cpp",
167
+ ".h",
168
+ ".hpp",
169
+ // C/C++
170
+ ".rs",
171
+ ".swift",
172
+ ".kt",
173
+ // modern langs
174
+ ".mdx"
175
+ // mdx docs
176
+ ]);
177
+ var MAX_ITEM_CHARS = 5e4;
178
+ var TARGET_CHUNK_CHARS = 8e3;
179
+ var MAX_BATCH_BYTES = 2e6;
180
+ var MAX_BATCH_COUNT = 100;
181
+ var BATCH_SLEEP_MS = 150;
182
+ function sleep2(ms) {
183
+ return new Promise((resolve) => setTimeout(resolve, ms));
184
+ }
185
+ function chunkText(text, maxChars) {
186
+ if (text.length <= maxChars) return [text];
187
+ const chunks = [];
188
+ const lines = text.split("\n");
189
+ let current = "";
190
+ for (const line of lines) {
191
+ if (current.length + line.length + 1 > maxChars && current.length > 0) {
192
+ chunks.push(current.trim());
193
+ current = "";
194
+ }
195
+ current += line + "\n";
196
+ }
197
+ if (current.trim()) chunks.push(current.trim());
198
+ return chunks;
199
+ }
200
+ async function fileToLines(filePath) {
201
+ const content = await fsp.readFile(filePath, "utf-8");
202
+ const stat = await fsp.stat(filePath);
203
+ const timestamp = Math.floor(stat.mtimeMs);
204
+ const filename = path2.basename(filePath);
205
+ const trimmed = content.trim();
206
+ if (trimmed.length < 50) return [];
207
+ if (trimmed.length <= MAX_ITEM_CHARS) {
208
+ return [{
209
+ content: `[${filename}] ${trimmed}`,
210
+ role: "user",
211
+ timestamp
212
+ }];
213
+ }
214
+ const chunks = chunkText(trimmed, TARGET_CHUNK_CHARS);
215
+ return chunks.map((chunk, i) => ({
216
+ content: `[${filename} part ${i + 1}/${chunks.length}] ${chunk}`,
217
+ role: "user",
218
+ timestamp
219
+ }));
220
+ }
221
+ async function sessionFileToLines(filePath) {
222
+ const content = await fsp.readFile(filePath, "utf-8");
223
+ const lines = [];
224
+ for (const line of content.split("\n")) {
225
+ if (!line.trim()) continue;
226
+ try {
227
+ const parsed = JSON.parse(line);
228
+ if (parsed.type !== "message") continue;
229
+ const msg = parsed.message;
230
+ if (!msg?.role || msg.role !== "user" && msg.role !== "assistant") continue;
231
+ let text = "";
232
+ if (typeof msg.content === "string") {
233
+ text = msg.content;
234
+ } else if (Array.isArray(msg.content)) {
235
+ text = msg.content.filter((b) => b.type === "text").map((b) => b.text).join("\n");
236
+ }
237
+ if (!text || text.trim().length < 20) continue;
238
+ let timestamp;
239
+ if (typeof parsed.timestamp === "string") timestamp = new Date(parsed.timestamp).getTime();
240
+ else if (typeof parsed.timestamp === "number") timestamp = parsed.timestamp;
241
+ else timestamp = Date.now();
242
+ lines.push({ content: text.trim(), role: msg.role, timestamp });
243
+ } catch {
244
+ }
245
+ }
246
+ return lines;
247
+ }
248
+ async function discoverFiles(dirPath) {
249
+ const files = [];
250
+ const entries = await fsp.readdir(dirPath, { recursive: true });
251
+ for (const entry of entries) {
252
+ const ext = path2.extname(entry).toLowerCase();
253
+ if (SUPPORTED_EXTENSIONS.has(ext) || ext === ".jsonl") {
254
+ const fullPath = path2.join(dirPath, entry);
255
+ const stat = await fsp.stat(fullPath);
256
+ if (stat.isFile() && stat.size > 0 && stat.size < 1e7) {
257
+ files.push(fullPath);
258
+ }
259
+ }
260
+ }
261
+ return files;
262
+ }
263
+ function formatTokens(tokens) {
264
+ if (tokens >= 1e6) return `${(tokens / 1e6).toFixed(1)}M`;
265
+ if (tokens >= 1e3) return `${(tokens / 1e3).toFixed(1)}K`;
266
+ return tokens.toString();
267
+ }
268
+ async function runUpload(targetPath, options) {
269
+ const config = requireConfig();
270
+ const baseUrl = getEndpoint(config);
271
+ const uploadUrl = `${baseUrl}/v1/memory/upload`;
272
+ const resolved = path2.resolve(targetPath);
273
+ if (!fs2.existsSync(resolved)) {
274
+ console.error(`\u274C Path not found: ${resolved}`);
275
+ process.exit(1);
276
+ }
277
+ const stat = fs2.statSync(resolved);
278
+ let files;
279
+ if (stat.isDirectory()) {
280
+ files = await discoverFiles(resolved);
281
+ } else {
282
+ files = [resolved];
283
+ }
284
+ if (files.length === 0) {
285
+ console.log("No supported files found.");
286
+ return;
287
+ }
288
+ console.log(`\u{1F4E4} Uploading ${files.length} file${files.length > 1 ? "s" : ""} to MemoryRouter...`);
289
+ if (options.session) {
290
+ console.log(` Session: ${options.session}`);
291
+ }
292
+ const allLines = [];
293
+ let skipped = 0;
294
+ for (const file of files) {
295
+ const displayName = path2.relative(resolved, file) || path2.basename(file);
296
+ try {
297
+ const lines = file.endsWith(".jsonl") ? await sessionFileToLines(file) : await fileToLines(file);
298
+ if (lines.length === 0) {
299
+ skipped++;
300
+ continue;
301
+ }
302
+ allLines.push(...lines);
303
+ console.log(` ${displayName.padEnd(50, ".")} \u2713 (${lines.length} chunk${lines.length > 1 ? "s" : ""})`);
304
+ } catch (err) {
305
+ console.log(` ${displayName.padEnd(50, ".")} \u2717 ${err instanceof Error ? err.message : "Error"}`);
306
+ }
307
+ }
308
+ if (skipped > 0) {
309
+ console.log(` Skipped ${skipped} file${skipped > 1 ? "s" : ""} (too small or empty)`);
310
+ }
311
+ if (allLines.length === 0) {
312
+ console.log("\nNo content to upload.");
313
+ return;
314
+ }
315
+ const totalChars = allLines.reduce((sum, l) => sum + l.content.length, 0);
316
+ const estimatedTokens = Math.round(totalChars / 4);
317
+ console.log(`
318
+ Total: ${allLines.length} chunks (~${formatTokens(estimatedTokens)} tokens)`);
319
+ const batches = [];
320
+ let currentBatch = [];
321
+ let currentBytes = 0;
322
+ for (const line of allLines) {
323
+ const lineBytes = JSON.stringify(line).length + 1;
324
+ if (currentBytes + lineBytes > MAX_BATCH_BYTES || currentBatch.length >= MAX_BATCH_COUNT) {
325
+ if (currentBatch.length > 0) batches.push(currentBatch);
326
+ currentBatch = [line];
327
+ currentBytes = lineBytes;
328
+ } else {
329
+ currentBatch.push(line);
330
+ currentBytes += lineBytes;
331
+ }
332
+ }
333
+ if (currentBatch.length > 0) batches.push(currentBatch);
334
+ console.log(`
335
+ Sending ${batches.length} batch${batches.length > 1 ? "es" : ""}...`);
336
+ let totalProcessed = 0;
337
+ let totalFailed = 0;
338
+ const headers = {
339
+ Authorization: `Bearer ${config.key}`,
340
+ "Content-Type": "text/plain"
341
+ };
342
+ if (options.session) {
343
+ headers["X-Session-ID"] = options.session;
344
+ }
345
+ for (let i = 0; i < batches.length; i++) {
346
+ if (i > 0) await sleep2(BATCH_SLEEP_MS);
347
+ const batch = batches[i];
348
+ const jsonlBody = batch.map((line) => JSON.stringify(line)).join("\n");
349
+ if (batches.length > 1) {
350
+ process.stdout.write(` Batch ${i + 1}/${batches.length} (${batch.length} items)... `);
351
+ }
352
+ try {
353
+ const response = await fetchWithRetry(uploadUrl, {
354
+ method: "POST",
355
+ headers,
356
+ body: jsonlBody
357
+ }, `Batch ${i + 1}`);
358
+ const result = await response.json();
359
+ const stored = result.stats?.stored ?? result.stats?.inputItems ?? batch.length;
360
+ const failed = result.stats?.failed ?? 0;
361
+ totalProcessed += stored;
362
+ totalFailed += failed;
363
+ if (batches.length > 1) {
364
+ if (failed > 0) {
365
+ console.log(`\u26A0 ${stored} stored, ${failed} skipped`);
366
+ } else {
367
+ console.log(`\u2713 ${stored} stored`);
368
+ }
369
+ }
370
+ } catch (err) {
371
+ console.error(`
372
+ \u274C Batch ${i + 1} failed: ${err instanceof Error ? err.message : String(err)}`);
373
+ totalFailed += batch.length;
374
+ }
375
+ }
376
+ console.log(`
377
+ \u2705 ${totalProcessed} memories stored`);
378
+ if (totalFailed > 0) {
379
+ console.log(`\u26A0\uFE0F ${totalFailed} failed \u2014 run upload again to retry`);
380
+ }
381
+ }
382
+
383
+ // src/index.ts
384
+ var program = new Command();
385
+ program.name("memoryrouter").description("MemoryRouter CLI \u2014 add persistent memory to any LLM").version("0.1.0");
386
+ program.command("auth <key>").description("Authenticate with your MemoryRouter memory key").option("--endpoint <url>", "Custom API endpoint").action(async (key, opts) => {
387
+ if (!/^mk[_-]/.test(key)) {
388
+ console.error("\u274C Memory key must start with mk_ or mk-");
389
+ console.log(" Get yours at https://memoryrouter.ai");
390
+ process.exit(1);
391
+ }
392
+ const baseUrl = opts.endpoint ? opts.endpoint.replace(/\/v1$/, "") : "https://api.memoryrouter.ai";
393
+ process.stdout.write("Validating key... ");
394
+ const valid = await validateKey(key, baseUrl);
395
+ if (!valid) {
396
+ console.log("\u26A0\uFE0F Could not validate (API may be temporarily unavailable)");
397
+ } else {
398
+ console.log("\u2713");
399
+ }
400
+ saveConfig({
401
+ key,
402
+ ...opts.endpoint ? { endpoint: opts.endpoint } : {}
403
+ });
404
+ console.log(`
405
+ \u2705 Authenticated as ${maskKey(key)}`);
406
+ console.log(` Config saved to ~/.memoryrouter/config.json`);
407
+ console.log(`
408
+ Next: memoryrouter upload ./docs/`);
409
+ });
410
+ program.command("upload <path>").description("Upload files or directories to your memory vault").option("-s, --session <id>", "Upload to a specific session vault instead of core").action(async (targetPath, opts) => {
411
+ await runUpload(targetPath, opts);
412
+ });
413
+ program.command("status").description("Show vault stats and connection status").option("--json", "Output as JSON").action(async (opts) => {
414
+ const config = requireConfig();
415
+ const baseUrl = getEndpoint(config);
416
+ const stats = await fetchStats(config.key, baseUrl);
417
+ if (opts.json) {
418
+ console.log(JSON.stringify({
419
+ key: maskKey(config.key),
420
+ endpoint: baseUrl,
421
+ stats
422
+ }, null, 2));
423
+ return;
424
+ }
425
+ console.log("MemoryRouter Status");
426
+ console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");
427
+ console.log(`Key: ${maskKey(config.key)}`);
428
+ console.log(`Endpoint: ${baseUrl}`);
429
+ if (stats) {
430
+ console.log("");
431
+ console.log("Vault:");
432
+ console.log(` Memories: ${stats.memories.toLocaleString()}`);
433
+ console.log(` Tokens: ${formatTokens2(stats.tokens)}`);
434
+ console.log(` Sessions: ${stats.sessions}`);
435
+ } else {
436
+ console.log("\n\u26A0\uFE0F Could not fetch vault stats");
437
+ }
438
+ });
439
+ program.command("delete").description("Clear all memories from vault").option("-s, --session <id>", "Delete a specific session vault only").option("-y, --yes", "Skip confirmation").action(async (opts) => {
440
+ const config = requireConfig();
441
+ const baseUrl = getEndpoint(config);
442
+ const target = opts.session ? `session "${opts.session}"` : "entire vault";
443
+ if (!opts.yes) {
444
+ process.stdout.write(`\u26A0\uFE0F This will delete your ${target}. Continue? (y/N) `);
445
+ const answer = await readLine();
446
+ if (answer.toLowerCase() !== "y") {
447
+ console.log("Cancelled.");
448
+ return;
449
+ }
450
+ }
451
+ console.log(`\u{1F5D1}\uFE0F Clearing ${target}...`);
452
+ const result = await deleteVault(config.key, baseUrl, opts.session);
453
+ if (result.success) {
454
+ console.log(`\u2705 ${result.message}`);
455
+ } else {
456
+ console.error(`\u274C Delete failed: ${result.message}`);
457
+ process.exit(1);
458
+ }
459
+ });
460
+ program.command("whoami").description("Show current authentication").action(() => {
461
+ const config = loadConfig();
462
+ if (!config?.key) {
463
+ console.log("Not authenticated. Run: memoryrouter auth <key>");
464
+ process.exit(1);
465
+ }
466
+ console.log(`Key: ${maskKey(config.key)}`);
467
+ console.log(`Endpoint: ${getEndpoint(config)}`);
468
+ });
469
+ function formatTokens2(tokens) {
470
+ if (tokens >= 1e6) return `${(tokens / 1e6).toFixed(1)}M`;
471
+ if (tokens >= 1e3) return `${(tokens / 1e3).toFixed(1)}K`;
472
+ return tokens.toString();
473
+ }
474
+ function readLine() {
475
+ return new Promise((resolve) => {
476
+ const { stdin } = process;
477
+ stdin.setEncoding("utf-8");
478
+ stdin.once("data", (data) => {
479
+ resolve(data.toString().trim());
480
+ });
481
+ stdin.resume();
482
+ });
483
+ }
484
+ program.parse();
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "@memoryrouter/cli",
3
+ "version": "0.1.0",
4
+ "description": "MemoryRouter CLI — add persistent memory to any LLM",
5
+ "type": "module",
6
+ "bin": {
7
+ "memoryrouter": "./dist/index.js"
8
+ },
9
+ "scripts": {
10
+ "build": "tsup src/index.ts --format esm --dts --clean",
11
+ "dev": "tsx src/index.ts"
12
+ },
13
+ "files": [
14
+ "dist"
15
+ ],
16
+ "keywords": [
17
+ "memoryrouter",
18
+ "memory",
19
+ "llm",
20
+ "ai",
21
+ "cli",
22
+ "vector",
23
+ "rag"
24
+ ],
25
+ "author": "MemoryRouter <hello@memoryrouter.ai>",
26
+ "license": "MIT",
27
+ "homepage": "https://memoryrouter.ai",
28
+ "repository": {
29
+ "type": "git",
30
+ "url": "git+https://github.com/John-Rood/MemoryRouter.git"
31
+ },
32
+ "dependencies": {
33
+ "commander": "^12.0.0"
34
+ },
35
+ "devDependencies": {
36
+ "@types/node": "^22.0.0",
37
+ "tsup": "^8.0.0",
38
+ "tsx": "^4.0.0",
39
+ "typescript": "^5.5.0"
40
+ }
41
+ }