memax-cli 0.1.0-alpha.2 → 0.1.0-alpha.20

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 (97) hide show
  1. package/assets/skills/memax-memory/SKILL.md +154 -0
  2. package/dist/commands/auth.d.ts +1 -0
  3. package/dist/commands/auth.d.ts.map +1 -1
  4. package/dist/commands/auth.js +14 -7
  5. package/dist/commands/auth.js.map +1 -1
  6. package/dist/commands/capture.d.ts +17 -0
  7. package/dist/commands/capture.d.ts.map +1 -0
  8. package/dist/commands/capture.js +60 -0
  9. package/dist/commands/capture.js.map +1 -0
  10. package/dist/commands/delete.d.ts +1 -1
  11. package/dist/commands/delete.d.ts.map +1 -1
  12. package/dist/commands/delete.js +22 -5
  13. package/dist/commands/delete.js.map +1 -1
  14. package/dist/commands/hub.d.ts +4 -0
  15. package/dist/commands/hub.d.ts.map +1 -0
  16. package/dist/commands/hub.js +53 -0
  17. package/dist/commands/hub.js.map +1 -0
  18. package/dist/commands/list.d.ts +2 -1
  19. package/dist/commands/list.d.ts.map +1 -1
  20. package/dist/commands/list.js +35 -8
  21. package/dist/commands/list.js.map +1 -1
  22. package/dist/commands/login.d.ts.map +1 -1
  23. package/dist/commands/login.js +32 -7
  24. package/dist/commands/login.js.map +1 -1
  25. package/dist/commands/mcp.d.ts.map +1 -1
  26. package/dist/commands/mcp.js +226 -26
  27. package/dist/commands/mcp.js.map +1 -1
  28. package/dist/commands/push.d.ts +2 -1
  29. package/dist/commands/push.d.ts.map +1 -1
  30. package/dist/commands/push.js +49 -11
  31. package/dist/commands/push.js.map +1 -1
  32. package/dist/commands/recall.d.ts +1 -0
  33. package/dist/commands/recall.d.ts.map +1 -1
  34. package/dist/commands/recall.js +30 -27
  35. package/dist/commands/recall.js.map +1 -1
  36. package/dist/commands/setup-hooks.d.ts +12 -0
  37. package/dist/commands/setup-hooks.d.ts.map +1 -0
  38. package/dist/commands/setup-hooks.js +184 -0
  39. package/dist/commands/setup-hooks.js.map +1 -0
  40. package/dist/commands/setup-instructions.d.ts +21 -0
  41. package/dist/commands/setup-instructions.d.ts.map +1 -0
  42. package/dist/commands/setup-instructions.js +172 -0
  43. package/dist/commands/setup-instructions.js.map +1 -0
  44. package/dist/commands/setup-mcp.d.ts +14 -0
  45. package/dist/commands/setup-mcp.d.ts.map +1 -0
  46. package/dist/commands/setup-mcp.js +276 -0
  47. package/dist/commands/setup-mcp.js.map +1 -0
  48. package/dist/commands/setup-types.d.ts +20 -0
  49. package/dist/commands/setup-types.d.ts.map +1 -0
  50. package/dist/commands/setup-types.js +60 -0
  51. package/dist/commands/setup-types.js.map +1 -0
  52. package/dist/commands/setup.d.ts +18 -0
  53. package/dist/commands/setup.d.ts.map +1 -0
  54. package/dist/commands/setup.js +371 -0
  55. package/dist/commands/setup.js.map +1 -0
  56. package/dist/commands/show.d.ts.map +1 -1
  57. package/dist/commands/show.js +10 -13
  58. package/dist/commands/show.js.map +1 -1
  59. package/dist/commands/sync.d.ts +7 -2
  60. package/dist/commands/sync.d.ts.map +1 -1
  61. package/dist/commands/sync.js +587 -107
  62. package/dist/commands/sync.js.map +1 -1
  63. package/dist/index.js +85 -14
  64. package/dist/index.js.map +1 -1
  65. package/dist/lib/client.d.ts +6 -0
  66. package/dist/lib/client.d.ts.map +1 -0
  67. package/dist/lib/client.js +69 -0
  68. package/dist/lib/client.js.map +1 -0
  69. package/dist/lib/project-context.d.ts +40 -0
  70. package/dist/lib/project-context.d.ts.map +1 -0
  71. package/dist/lib/project-context.js +157 -0
  72. package/dist/lib/project-context.js.map +1 -0
  73. package/dist/lib/prompt.d.ts +7 -0
  74. package/dist/lib/prompt.d.ts.map +1 -0
  75. package/dist/lib/prompt.js +41 -0
  76. package/dist/lib/prompt.js.map +1 -0
  77. package/package.json +17 -13
  78. package/dist/lib/api.d.ts +0 -4
  79. package/dist/lib/api.d.ts.map +0 -1
  80. package/dist/lib/api.js +0 -95
  81. package/dist/lib/api.js.map +0 -1
  82. package/src/commands/auth.ts +0 -92
  83. package/src/commands/config.ts +0 -27
  84. package/src/commands/delete.ts +0 -20
  85. package/src/commands/hook.ts +0 -243
  86. package/src/commands/list.ts +0 -38
  87. package/src/commands/login.ts +0 -159
  88. package/src/commands/mcp.ts +0 -282
  89. package/src/commands/push.ts +0 -82
  90. package/src/commands/recall.ts +0 -160
  91. package/src/commands/show.ts +0 -35
  92. package/src/commands/sync.ts +0 -403
  93. package/src/index.ts +0 -167
  94. package/src/lib/api.ts +0 -110
  95. package/src/lib/config.ts +0 -61
  96. package/src/lib/credentials.ts +0 -42
  97. package/tsconfig.json +0 -9
@@ -1,35 +0,0 @@
1
- import chalk from "chalk";
2
- import { apiGet } from "../lib/api.js";
3
- import type { Note } from "@memaxlabs/shared";
4
-
5
- export async function showCommand(id: string): Promise<void> {
6
- if (!id) {
7
- console.error(chalk.red("Provide a note ID: memax show <id>"));
8
- process.exit(1);
9
- }
10
-
11
- try {
12
- const note = await apiGet<Note>(`/v1/notes/${id}`);
13
-
14
- console.log(chalk.bold(note.title));
15
- console.log(
16
- chalk.gray(
17
- `${note.category} · ${note.source} · v${note.version} · ${note.state}`,
18
- ),
19
- );
20
- if (note.tags?.length) {
21
- console.log(chalk.gray(`tags: ${note.tags.join(", ")}`));
22
- }
23
- console.log(chalk.gray(`id: ${note.id}`));
24
- console.log();
25
- // API returns content inline; the shared Note type doesn't include it
26
- // because production stores content in R2. Cast to access it.
27
- const content = (note as Note & { content?: string }).content;
28
- if (content) {
29
- console.log(content);
30
- }
31
- } catch (err) {
32
- console.error(chalk.red(`Show failed: ${(err as Error).message}`));
33
- process.exit(1);
34
- }
35
- }
@@ -1,403 +0,0 @@
1
- import chalk from "chalk";
2
- import {
3
- readFileSync,
4
- readdirSync,
5
- statSync,
6
- watch,
7
- existsSync,
8
- } from "node:fs";
9
- import { join, relative, extname, resolve, basename } from "node:path";
10
- import { homedir } from "node:os";
11
- import { apiPost } from "../lib/api.js";
12
- import type { Note } from "@memaxlabs/shared";
13
-
14
- interface SyncOptions {
15
- boundary?: string;
16
- category?: string;
17
- watch?: boolean;
18
- ignore?: string;
19
- agentMemory?: boolean;
20
- }
21
-
22
- const DEFAULT_IGNORE = new Set([
23
- "node_modules",
24
- ".git",
25
- ".next",
26
- "dist",
27
- "__pycache__",
28
- ".env",
29
- ".env.local",
30
- ".DS_Store",
31
- ]);
32
-
33
- const SUPPORTED_EXTENSIONS = new Set([
34
- ".md",
35
- ".txt",
36
- ".ts",
37
- ".tsx",
38
- ".js",
39
- ".jsx",
40
- ".go",
41
- ".py",
42
- ".rs",
43
- ".yaml",
44
- ".yml",
45
- ".json",
46
- ".toml",
47
- ".sh",
48
- ".bash",
49
- ".zsh",
50
- ".css",
51
- ".html",
52
- ".sql",
53
- ".graphql",
54
- ".proto",
55
- ".dockerfile",
56
- ]);
57
-
58
- export async function syncAgentMemoryCommand(): Promise<void> {
59
- await syncAgentMemory();
60
- }
61
-
62
- export async function syncCommand(
63
- directory: string | undefined,
64
- options: SyncOptions,
65
- ): Promise<void> {
66
- if (options.agentMemory || directory === "agents") {
67
- await syncAgentMemory();
68
- return;
69
- }
70
-
71
- const dir = directory ?? ".";
72
-
73
- const customIgnore = options.ignore
74
- ? new Set(options.ignore.split(",").map((s) => s.trim()))
75
- : new Set<string>();
76
- const ignoreSet = new Set([...DEFAULT_IGNORE, ...customIgnore]);
77
-
78
- console.log(chalk.blue("Scanning"), dir);
79
-
80
- const files = walkDir(dir, ignoreSet);
81
-
82
- if (files.length === 0) {
83
- console.log(chalk.yellow("No supported files found."));
84
- return;
85
- }
86
-
87
- console.log(chalk.gray(`Found ${files.length} files to sync`));
88
- console.log();
89
-
90
- let pushed = 0;
91
- let errors = 0;
92
-
93
- for (const file of files) {
94
- const result = await pushFile(file, options);
95
- if (result === "pushed") pushed++;
96
- else if (result === "error") errors++;
97
- }
98
-
99
- console.log();
100
- console.log(
101
- chalk.blue(`Synced ${pushed} files`),
102
- errors > 0 ? chalk.red(`(${errors} errors)`) : "",
103
- );
104
-
105
- if (options.watch) {
106
- const resolvedDir = resolve(dir);
107
- console.log(
108
- chalk.cyan(`\nWatching ${dir} for changes... (Ctrl+C to stop)`),
109
- );
110
-
111
- let debounceTimer: NodeJS.Timeout | null = null;
112
- const pendingChanges = new Set<string>();
113
-
114
- watch(resolvedDir, { recursive: true }, (_eventType, filename) => {
115
- if (!filename) return;
116
- const fullPath = join(resolvedDir, filename);
117
-
118
- if (!isSupportedFile(filename) || isIgnored(filename, ignoreSet)) return;
119
-
120
- pendingChanges.add(fullPath);
121
- if (debounceTimer) clearTimeout(debounceTimer);
122
- debounceTimer = setTimeout(async () => {
123
- for (const file of pendingChanges) {
124
- if (!existsSync(file)) {
125
- console.log(
126
- chalk.gray(" ~"),
127
- relative(process.cwd(), file),
128
- chalk.gray("[deleted, skipped]"),
129
- );
130
- continue;
131
- }
132
- await pushFile(file, options);
133
- }
134
- pendingChanges.clear();
135
- }, 500);
136
- });
137
- }
138
- }
139
-
140
- async function pushFile(
141
- file: string,
142
- options: SyncOptions,
143
- ): Promise<"pushed" | "skipped" | "error"> {
144
- try {
145
- const content = readFileSync(file, "utf-8");
146
- if (!content.trim()) return "skipped";
147
-
148
- const relPath = relative(process.cwd(), file);
149
- const ext = extname(file);
150
- const contentType =
151
- ext === ".md"
152
- ? "markdown"
153
- : ext === ".json" || ext === ".yaml" || ext === ".yml"
154
- ? "structured"
155
- : "code";
156
-
157
- const note = await apiPost<Note>("/v1/notes", {
158
- content,
159
- title: relPath,
160
- category: options.category ?? guessCategory(relPath),
161
- source: "sync",
162
- source_path: relPath,
163
- content_type: contentType,
164
- });
165
-
166
- console.log(chalk.green(" +"), relPath, chalk.gray(`[${note.category}]`));
167
- return "pushed";
168
- } catch (err) {
169
- console.log(chalk.red(" x"), file, chalk.gray((err as Error).message));
170
- return "error";
171
- }
172
- }
173
-
174
- function isSupportedFile(filename: string): boolean {
175
- return SUPPORTED_EXTENSIONS.has(extname(filename));
176
- }
177
-
178
- function isIgnored(filename: string, ignoreSet: Set<string>): boolean {
179
- const parts = filename.split(/[/\\]/);
180
- return parts.some((part) => ignoreSet.has(part) || part.startsWith("."));
181
- }
182
-
183
- function walkDir(dir: string, ignore: Set<string>): string[] {
184
- const files: string[] = [];
185
-
186
- function walk(currentDir: string): void {
187
- let entries: string[];
188
- try {
189
- entries = readdirSync(currentDir);
190
- } catch {
191
- return;
192
- }
193
-
194
- for (const entry of entries) {
195
- if (ignore.has(entry) || entry.startsWith(".")) continue;
196
-
197
- const fullPath = join(currentDir, entry);
198
- let stat;
199
- try {
200
- stat = statSync(fullPath);
201
- } catch {
202
- continue;
203
- }
204
-
205
- if (stat.isDirectory()) {
206
- walk(fullPath);
207
- } else if (stat.isFile() && SUPPORTED_EXTENSIONS.has(extname(entry))) {
208
- files.push(fullPath);
209
- }
210
- }
211
- }
212
-
213
- walk(dir);
214
- return files;
215
- }
216
-
217
- function guessCategory(path: string): string {
218
- const lower = path.toLowerCase();
219
- if (lower.includes("adr") || lower.includes("decision"))
220
- return "decisions/adr";
221
- if (lower.includes("deploy") || lower.includes("ci")) return "process/deploy";
222
- if (lower.includes("architecture") || lower.includes("design"))
223
- return "core/architecture";
224
- if (lower.includes("readme") || lower.includes("docs"))
225
- return "reference/api";
226
- if (lower.includes("test")) return "reference/api";
227
- if (lower.includes("config") || lower.includes(".env"))
228
- return "reference/config";
229
- return "daily/note";
230
- }
231
-
232
- // --- Agent memory sync ---
233
-
234
- interface AgentMemoryLocation {
235
- label: string;
236
- path: string;
237
- }
238
-
239
- function discoverAgentMemoryFiles(): AgentMemoryLocation[] {
240
- const home = homedir();
241
- const cwd = process.cwd();
242
- const locations: AgentMemoryLocation[] = [];
243
-
244
- // Claude Code global memory
245
- const claudeMemory = join(home, ".claude", "MEMORY.md");
246
- locations.push({ label: "~/.claude/MEMORY.md", path: claudeMemory });
247
-
248
- // Claude Code per-project memories: ~/.claude/projects/*/memory/*.md
249
- const claudeProjectsDir = join(home, ".claude", "projects");
250
- if (existsSync(claudeProjectsDir)) {
251
- try {
252
- for (const project of readdirSync(claudeProjectsDir)) {
253
- const memoryDir = join(claudeProjectsDir, project, "memory");
254
- if (existsSync(memoryDir)) {
255
- try {
256
- for (const file of readdirSync(memoryDir)) {
257
- if (file.endsWith(".md")) {
258
- locations.push({
259
- label: `~/.claude/projects/${project}/memory/${file}`,
260
- path: join(memoryDir, file),
261
- });
262
- }
263
- }
264
- } catch {
265
- // Permission denied or other read error — skip
266
- }
267
- }
268
- }
269
- } catch {
270
- // Permission denied or other read error — skip
271
- }
272
- }
273
-
274
- // Cursor rules (project-level)
275
- locations.push({ label: "./.cursorrules", path: join(cwd, ".cursorrules") });
276
-
277
- // Cursor scoped rules: .cursor/rules/*.mdc
278
- const cursorRulesDir = join(cwd, ".cursor", "rules");
279
- if (existsSync(cursorRulesDir)) {
280
- try {
281
- for (const file of readdirSync(cursorRulesDir)) {
282
- if (file.endsWith(".mdc")) {
283
- locations.push({
284
- label: `./.cursor/rules/${file}`,
285
- path: join(cursorRulesDir, file),
286
- });
287
- }
288
- }
289
- } catch {
290
- // Skip on error
291
- }
292
- }
293
-
294
- // Codex instructions
295
- locations.push({
296
- label: "./.codex/instructions.md",
297
- path: join(cwd, ".codex", "instructions.md"),
298
- });
299
-
300
- // Generic agent config files in current directory
301
- locations.push({ label: "./AGENTS.md", path: join(cwd, "AGENTS.md") });
302
- locations.push({ label: "./CLAUDE.md", path: join(cwd, "CLAUDE.md") });
303
-
304
- return locations;
305
- }
306
-
307
- function formatFileSize(bytes: number): string {
308
- if (bytes < 1024) return `${bytes} B`;
309
- return `${(bytes / 1024).toFixed(1)} KB`;
310
- }
311
-
312
- async function syncAgentMemory(): Promise<void> {
313
- console.log(chalk.blue("Scanning for agent memory files..."));
314
- console.log();
315
-
316
- const locations = discoverAgentMemoryFiles();
317
- const found: { label: string; path: string; size: number }[] = [];
318
- const notFound: string[] = [];
319
-
320
- for (const loc of locations) {
321
- if (existsSync(loc.path)) {
322
- try {
323
- const stat = statSync(loc.path);
324
- if (stat.isFile() && stat.size > 0) {
325
- found.push({ label: loc.label, path: loc.path, size: stat.size });
326
- } else {
327
- notFound.push(loc.label);
328
- }
329
- } catch {
330
- notFound.push(loc.label);
331
- }
332
- } else {
333
- notFound.push(loc.label);
334
- }
335
- }
336
-
337
- if (found.length === 0) {
338
- console.log(chalk.yellow("No agent memory files found."));
339
- return;
340
- }
341
-
342
- console.log("Found:");
343
-
344
- for (const f of found) {
345
- console.log(
346
- chalk.green(" \u2713"),
347
- f.label,
348
- chalk.gray(`(${formatFileSize(f.size)})`),
349
- );
350
- }
351
- for (const label of notFound) {
352
- console.log(
353
- chalk.gray(" \u2717"),
354
- chalk.gray(label),
355
- chalk.gray("(not found)"),
356
- );
357
- }
358
-
359
- console.log();
360
-
361
- let synced = 0;
362
- let unchanged = 0;
363
- let errors = 0;
364
-
365
- for (const f of found) {
366
- try {
367
- const content = readFileSync(f.path, "utf-8");
368
- if (!content.trim()) continue;
369
-
370
- const title = basename(f.path);
371
-
372
- await apiPost<Note>("/v1/notes", {
373
- content,
374
- title,
375
- source: "sync",
376
- source_path: f.path,
377
- content_type: "markdown",
378
- category: "",
379
- });
380
-
381
- synced++;
382
- } catch (err) {
383
- const msg = (err as Error).message;
384
- if (
385
- msg.includes("unchanged") ||
386
- msg.includes("duplicate") ||
387
- msg.includes("exists")
388
- ) {
389
- unchanged++;
390
- } else {
391
- errors++;
392
- console.log(chalk.red(" Error syncing"), f.label, chalk.gray(msg));
393
- }
394
- }
395
- }
396
-
397
- console.log(
398
- chalk.blue(`Synced ${found.length} files to Memax`),
399
- chalk.gray(
400
- `(${synced} new, ${unchanged} unchanged${errors > 0 ? `, ${errors} errors` : ""})`,
401
- ),
402
- );
403
- }
package/src/index.ts DELETED
@@ -1,167 +0,0 @@
1
- #!/usr/bin/env node
2
- import { Command } from "commander";
3
- import { pushCommand } from "./commands/push.js";
4
- import { recallCommand } from "./commands/recall.js";
5
- import { listCommand } from "./commands/list.js";
6
- import { showCommand } from "./commands/show.js";
7
- import { deleteCommand } from "./commands/delete.js";
8
- import { syncCommand, syncAgentMemoryCommand } from "./commands/sync.js";
9
- import { hookCommand } from "./commands/hook.js";
10
- import { configGetCommand, configSetCommand } from "./commands/config.js";
11
- import {
12
- loginCommand,
13
- logoutCommand,
14
- whoamiCommand,
15
- } from "./commands/login.js";
16
- import {
17
- createKeyCommand,
18
- listKeysCommand,
19
- revokeKeyCommand,
20
- } from "./commands/auth.js";
21
- import { registerMcpCommand } from "./commands/mcp.js";
22
-
23
- const program = new Command();
24
-
25
- program
26
- .name("memax")
27
- .description("Universal context & memory hub for AI agents")
28
- .version("0.0.1");
29
-
30
- // --- Core commands ---
31
-
32
- program
33
- .command("push")
34
- .description("Save knowledge to your Memax workspace")
35
- .option("-f, --file <path>", "File to push")
36
- .option("-c, --category <category>", "Category (auto-detected if omitted)")
37
- .option("-t, --tags <tags>", "Comma-separated tags")
38
- .option("--title <title>", "Note title")
39
- .option("--ttl <duration>", "Auto-archive after duration (e.g., 7d, 30d)")
40
- .option("--stdin", "Read content from stdin")
41
- .action(pushCommand);
42
-
43
- program
44
- .command("recall [query]")
45
- .description("Ask your knowledge a question")
46
- .option("-c, --category <category>", "Filter by category")
47
- .option("-t, --tags <tags>", "Filter by tags")
48
- .option("-l, --limit <n>", "Max results", "5")
49
- .option("--format <format>", "Output format: text, json", "text")
50
- .option("--hook", "Output in agent-injectable format")
51
- .option("--max-tokens <number>", "Maximum tokens to output (approximate)")
52
- .option("--include-archived", "Include archived notes")
53
- .action(recallCommand);
54
-
55
- program
56
- .command("list")
57
- .description("List your knowledge notes")
58
- .option("-c, --category <category>", "Filter by category")
59
- .option("--state <state>", "Filter by state: active, cooling, archived")
60
- .option("-l, --limit <n>", "Max results", "20")
61
- .action(listCommand);
62
-
63
- program
64
- .command("show <id>")
65
- .description("Show a specific note")
66
- .action(showCommand);
67
-
68
- program
69
- .command("delete <id>")
70
- .description("Delete a note")
71
- .option("--confirm", "Skip confirmation")
72
- .action(deleteCommand);
73
-
74
- // --- Sync ---
75
-
76
- const syncCmd = program
77
- .command("sync [directory]")
78
- .description("Sync a directory or agent memory to your Memax workspace")
79
- .option("-w, --watch", "Watch for changes (coming soon)")
80
- .option(
81
- "-b, --boundary <level>",
82
- "Visibility level: private, team, org",
83
- "private",
84
- )
85
- .option(
86
- "-c, --category <category>",
87
- "Default category (auto-detected if omitted)",
88
- )
89
- .option("--ignore <patterns>", "Comma-separated directories to ignore")
90
- .option(
91
- "--agent-memory",
92
- "Sync native AI agent memory files (Claude Code, Cursor, Codex)",
93
- )
94
- .action(syncCommand);
95
-
96
- syncCmd
97
- .command("agents")
98
- .description("Sync native AI agent memory files to Memax")
99
- .action(syncAgentMemoryCommand);
100
-
101
- // --- Agent hooks ---
102
-
103
- program
104
- .command("hook <action> <agent>")
105
- .description("Manage agent hooks (install/uninstall claude-code)")
106
- .action(hookCommand);
107
-
108
- // --- Auth ---
109
-
110
- program
111
- .command("login")
112
- .description("Log in to Memax via GitHub")
113
- .action(loginCommand);
114
-
115
- program
116
- .command("logout")
117
- .description("Clear saved credentials")
118
- .action(logoutCommand);
119
-
120
- program
121
- .command("whoami")
122
- .description("Show current user")
123
- .action(whoamiCommand);
124
-
125
- // --- API Keys ---
126
-
127
- const authCmd = program
128
- .command("auth")
129
- .description("Manage authentication and API keys");
130
-
131
- authCmd
132
- .command("create-key <name>")
133
- .description("Create an API key for CI/CD or non-interactive use")
134
- .option("--expires <days>", "Expire after N days (default: never)")
135
- .action(createKeyCommand);
136
-
137
- authCmd
138
- .command("list-keys")
139
- .description("List your API keys")
140
- .action(listKeysCommand);
141
-
142
- authCmd
143
- .command("revoke-key <id>")
144
- .description("Revoke an API key")
145
- .action(revokeKeyCommand);
146
-
147
- // --- MCP Server ---
148
-
149
- registerMcpCommand(program);
150
-
151
- // --- Config ---
152
-
153
- const configCmd = program
154
- .command("config")
155
- .description("Manage Memax configuration");
156
-
157
- configCmd
158
- .command("get [key]")
159
- .description("Get config value (or all values)")
160
- .action(configGetCommand);
161
-
162
- configCmd
163
- .command("set <key> <value>")
164
- .description("Set a config value")
165
- .action(configSetCommand);
166
-
167
- program.parse();
package/src/lib/api.ts DELETED
@@ -1,110 +0,0 @@
1
- import { loadConfig } from "./config.js";
2
- import {
3
- loadCredentials,
4
- saveCredentials,
5
- isTokenExpired,
6
- } from "./credentials.js";
7
-
8
- interface ApiEnvelope {
9
- data?: unknown;
10
- error?: { code: string; message: string };
11
- }
12
-
13
- function getApiUrl(): string {
14
- return loadConfig().api_url;
15
- }
16
-
17
- async function authHeaders(): Promise<Record<string, string>> {
18
- // 1. MEMAX_API_KEY env var takes priority (CI/CD, non-interactive)
19
- const envKey = process.env.MEMAX_API_KEY;
20
- if (envKey) {
21
- return { Authorization: `Bearer ${envKey}` };
22
- }
23
-
24
- // 2. Stored credentials with auto-refresh
25
- const creds = loadCredentials();
26
- if (!creds?.access_token) return {};
27
-
28
- if (isTokenExpired() && creds.refresh_token) {
29
- // Attempt to refresh the access token
30
- try {
31
- const url = `${getApiUrl()}/v1/auth/refresh`;
32
- const res = await fetch(url, {
33
- method: "POST",
34
- headers: { "Content-Type": "application/json" },
35
- body: JSON.stringify({ refresh_token: creds.refresh_token }),
36
- });
37
- const json = (await res.json()) as ApiEnvelope;
38
- if (json.data) {
39
- const tokens = json.data as {
40
- access_token: string;
41
- refresh_token: string;
42
- expires_in: number;
43
- };
44
- saveCredentials({
45
- access_token: tokens.access_token,
46
- refresh_token: tokens.refresh_token,
47
- expires_at: Date.now() + tokens.expires_in * 1000,
48
- });
49
- return { Authorization: `Bearer ${tokens.access_token}` };
50
- }
51
- } catch {
52
- // Refresh failed — fall through to use stale token (server will reject)
53
- }
54
- }
55
-
56
- return { Authorization: `Bearer ${creds.access_token}` };
57
- }
58
-
59
- export async function apiPost<T>(path: string, body: unknown): Promise<T> {
60
- const url = `${getApiUrl()}${path}`;
61
- let res: Response;
62
- try {
63
- res = await fetch(url, {
64
- method: "POST",
65
- headers: { "Content-Type": "application/json", ...(await authHeaders()) },
66
- body: JSON.stringify(body),
67
- });
68
- } catch {
69
- throw new Error(`Cannot reach API at ${url} — is the server running?`);
70
- }
71
- const json = (await res.json()) as ApiEnvelope;
72
- if (json.error) {
73
- throw new Error(json.error.message);
74
- }
75
- return json.data as T;
76
- }
77
-
78
- export async function apiGet<T>(path: string): Promise<T> {
79
- const url = `${getApiUrl()}${path}`;
80
- let res: Response;
81
- try {
82
- res = await fetch(url, {
83
- headers: { ...(await authHeaders()) },
84
- });
85
- } catch {
86
- throw new Error(`Cannot reach API at ${url} — is the server running?`);
87
- }
88
- const json = (await res.json()) as ApiEnvelope;
89
- if (json.error) {
90
- throw new Error(json.error.message);
91
- }
92
- return json.data as T;
93
- }
94
-
95
- export async function apiDelete(path: string): Promise<void> {
96
- const url = `${getApiUrl()}${path}`;
97
- let res: Response;
98
- try {
99
- res = await fetch(url, {
100
- method: "DELETE",
101
- headers: { ...(await authHeaders()) },
102
- });
103
- } catch {
104
- throw new Error(`Cannot reach API at ${url} — is the server running?`);
105
- }
106
- const json = (await res.json()) as ApiEnvelope;
107
- if (json.error) {
108
- throw new Error(json.error.message);
109
- }
110
- }