@audaxic/memory-claude 1.1.0 → 1.2.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.
package/README.md CHANGED
@@ -9,12 +9,14 @@ npx @audaxic/memory-claude install
9
9
  ```
10
10
 
11
11
  This will:
12
- 1. Prompt for your Audaxic API key (saved to `~/.config/audaxic/config.json`)
12
+ 1. Prompt for your Audaxic general API key (saved to `~/.config/audaxic/config.json`)
13
13
  2. Copy the plugin to `~/.claude/skills/audaxic-memory/`
14
- 3. Configure the Audaxic MCP server (`.mcp.json` with your API key)
14
+ 3. Configure the directory-aware Audaxic MCP proxy
15
15
 
16
16
  The plugin auto-loads on your next Claude Code session.
17
17
 
18
+ If you install from the plugin marketplace instead of the CLI, also run `npx @audaxic/memory-claude key set --global` once so the MCP proxy can read your general key from the shared config.
19
+
18
20
  Get your API key from: https://memory-dashboard.audaxic.com
19
21
 
20
22
  ## How It Works
@@ -27,26 +29,59 @@ An Agent Skill (`skills/audaxic-memory/SKILL.md`) instructs Claude to search Aud
27
29
 
28
30
  ### MCP server → trusted memory tools
29
31
 
30
- The plugin bundles the Audaxic MCP server (`.mcp.json`), giving Claude `search_memories` / `add_memory` / `get_memories` tools. MCP tool results are trusted by Claude, so memory recall actually reaches the answer.
32
+ The plugin configures a small local stdio proxy (`.mcp.json`). The proxy resolves the key for the session's project directory and connects to the hosted MCP server, so Claude gets `search_memories` / `add_memory` / `get_memories` tools scoped to the right project.
31
33
 
32
34
  ### Hooks → background saving
33
35
 
34
- - `UserPromptSubmit` → `inject.mjs`: saves your prompt immediately and injects context via `additionalContext` (a passive enhancement — injection may be deprioritized by Claude Code, which is why the skill + MCP path exists)
35
- - `Stop` → `capture.mjs`: saves the assistant's response immediately
36
+ - `UserPromptSubmit` → `inject.mjs`: parks your prompt to disk (no save wait) and injects context via `additionalContext` (a passive enhancement — injection may be deprioritized by Claude Code, which is why the skill + MCP path exists). Drains one stale parked message alongside the search.
37
+ - `Stop` → `capture.mjs`: parks the assistant's response, then drains up to 3 stale parked messages (25s timeout each, within the hook's 30s budget).
36
38
 
37
- Saving is crash-safe and parallel-safe: each message is written to its own parking file under `${CLAUDE_PLUGIN_DATA}/pending/` and deleted only after `POST /add` confirms receipt. Failed saves stay parked and are retried automatically (stale files, older than 60s, are claimed atomically). Multiple simultaneous Claude Code sessions never share or overwrite files.
39
+ Saving is park-only and crash-safe: each message is written to its own parking file under `${CLAUDE_PLUGIN_DATA}/pending/` and delivered by drain cycles; a file is deleted only after `POST /add` confirms receipt. Failed sends stay parked and retry on subsequent hooks (stale files >60s, atomic rename claims, abandoned claims healed after 5 minutes). Multiple simultaneous Claude Code sessions never share or overwrite files.
38
40
 
39
41
  ## API Key
40
42
 
41
43
  The plugin uses your API key in this order:
42
44
 
43
- 1. `CLAUDE_PLUGIN_OPTION_API_TOKEN` — set via the plugin's `userConfig` prompt during `/plugin install`
44
- 2. `~/.config/audaxic/config.json` — shared config used by all Audaxic integrations
45
-
46
- The key is also written into the plugin's `.mcp.json` at install time (mode 0600) so the MCP server authenticates automatically.
45
+ 1. `AUDAXIC_API_KEY` — explicit environment override for the current process
46
+ 2. `directoryKeys` entry matching the session project directory (`CLAUDE_PROJECT_DIR`)
47
+ 3. `CLAUDE_PLUGIN_OPTION_API_TOKEN` — the general key from the plugin's `userConfig` prompt
48
+ 4. `apiKey` — the general key in `~/.config/audaxic/config.json`
47
49
 
48
50
  All scripts fail silently if no key is found — they never block Claude Code.
49
51
 
52
+ ## Directory-specific API keys
53
+
54
+ Give each project its own memory project by mapping a directory to an API key. The key is scoped to one project on the server, so opening a directory uses that project automatically.
55
+
56
+ ```bash
57
+ # General fallback used outside mapped directories
58
+ npx @audaxic/memory-claude key set --global
59
+
60
+ # Inside a project directory: use that project's key
61
+ cd C:\projeler\my-project
62
+ npx @audaxic/memory-claude key set
63
+
64
+ # Inspect
65
+ npx @audaxic/memory-claude key list
66
+ npx @audaxic/memory-claude key resolve
67
+ ```
68
+
69
+ The shared config looks like this:
70
+
71
+ ```json
72
+ {
73
+ "apiKey": "ak_general...",
74
+ "directoryKeys": {
75
+ "C:\\projeler\\my-project": "ak_project_a...",
76
+ "C:\\projeler\\another-project": "ak_project_b..."
77
+ }
78
+ }
79
+ ```
80
+
81
+ Matching uses the nearest parent directory, so opening `my-project/packages/api` uses the `my-project` key unless a more specific entry exists. Git worktrees fall back to the main checkout's key; a worktree-specific entry overrides it. The config is stored in your user profile with mode `0600`; keys are never written into a repository.
82
+
83
+ Same directory means the same memory project across Claude Code, Codex, and OpenCode. Parallel sessions are safe: each parked message stores the key it was captured with, so a flush in one directory cannot send another directory's memory to the wrong project.
84
+
50
85
  ## Architecture
51
86
 
52
87
  ```
@@ -70,6 +105,16 @@ All scripts fail silently if no key is found — they never block Claude Code.
70
105
  └──────────────────────────────────────────────────────────────┘
71
106
  ```
72
107
 
108
+ ## Troubleshooting
109
+
110
+ Which key applies to the current directory?
111
+
112
+ ```bash
113
+ npx @audaxic/memory-claude key resolve
114
+ ```
115
+
116
+ It shows whether the directory key, environment override, plugin key, or general key won.
117
+
73
118
  ## Uninstall
74
119
 
75
120
  ```bash
package/bin/install.js CHANGED
@@ -4,7 +4,6 @@ import { createInterface } from "node:readline/promises";
4
4
  import { stdin, stdout } from "node:process";
5
5
  import {
6
6
  mkdir,
7
- readFile,
8
7
  writeFile,
9
8
  copyFile,
10
9
  access,
@@ -14,15 +13,21 @@ import {
14
13
  import { join, dirname } from "node:path";
15
14
  import { homedir } from "node:os";
16
15
  import { fileURLToPath } from "node:url";
16
+ import { runKeyCommand } from "../scripts/key-cli.mjs";
17
+ import {
18
+ displayPath,
19
+ getConfigPath,
20
+ maskKey,
21
+ readConfig,
22
+ setDirectoryKey,
23
+ setGlobalKey,
24
+ } from "../scripts/config.mjs";
17
25
 
18
26
  const __filename = fileURLToPath(import.meta.url);
19
27
  const __dirname = dirname(__filename);
20
28
 
21
29
  const PACKAGE_ROOT = join(__dirname, "..");
22
- const CONFIG_DIR = join(homedir(), ".config", "audaxic");
23
- const CONFIG_PATH = join(CONFIG_DIR, "config.json");
24
30
  const PLUGIN_DEST = join(homedir(), ".claude", "skills", "audaxic-memory");
25
- const MCP_ENDPOINT = "https://memory-mcp.audaxic.com/mcp";
26
31
 
27
32
  const DIRS_TO_COPY = [".claude-plugin", "hooks", "scripts", "skills"];
28
33
 
@@ -49,45 +54,27 @@ async function copyDir(src, dest) {
49
54
  }
50
55
  }
51
56
 
52
- async function loadApiKey() {
53
- try {
54
- const raw = await readFile(CONFIG_PATH, "utf-8");
55
- const config = JSON.parse(raw);
56
- if (typeof config.apiKey === "string" && config.apiKey.length > 0) {
57
- return config.apiKey;
58
- }
59
- } catch {}
60
- return null;
61
- }
62
-
63
57
  async function ensureApiKeyFile(rl) {
64
- if (await pathExists(CONFIG_PATH)) return;
58
+ const config = await readConfig();
59
+ if (typeof config.apiKey === "string" && config.apiKey.trim()) return;
65
60
  console.log(
66
- "\nNo Audaxic config found. Get your API key from: https://memory-dashboard.audaxic.com"
61
+ "\nNo Audaxic general API key found. Get one from: https://memory-dashboard.audaxic.com"
67
62
  );
68
63
  const apiKey = await rl.question("Enter your Audaxic API Key: ");
69
64
  if (!apiKey.trim()) {
70
65
  console.error("\nError: API key cannot be empty.");
71
66
  process.exit(1);
72
67
  }
73
- await mkdir(CONFIG_DIR, { recursive: true });
74
- await writeFile(
75
- CONFIG_PATH,
76
- JSON.stringify({ apiKey: apiKey.trim() }, null, 2),
77
- { mode: 0o600 }
78
- );
79
- console.log("✓ API key saved to ~/.config/audaxic/config.json");
68
+ await setGlobalKey(apiKey);
69
+ console.log(`✓ API key saved to ${getConfigPath()}`);
80
70
  }
81
71
 
82
- async function writeMcpConfig(apiKey) {
72
+ async function writeMcpConfig() {
83
73
  const mcpConfig = {
84
74
  mcpServers: {
85
75
  "audaxic-memory": {
86
- type: "http",
87
- url: MCP_ENDPOINT,
88
- headers: {
89
- Authorization: `Bearer ${apiKey}`,
90
- },
76
+ command: "node",
77
+ args: [join(PLUGIN_DEST, "scripts", "mcp-proxy.mjs")],
91
78
  },
92
79
  },
93
80
  };
@@ -99,6 +86,12 @@ async function writeMcpConfig(apiKey) {
99
86
  }
100
87
 
101
88
  async function main() {
89
+ const args = process.argv.slice(2);
90
+ if (args[0] === "key") {
91
+ await runKeyCommand(args.slice(1), { packageName: "@audaxic/memory-claude" });
92
+ return;
93
+ }
94
+
102
95
  console.log("\n╔══════════════════════════════════════════╗");
103
96
  console.log("║ Audaxic Memory — Claude Code Setup ║");
104
97
  console.log("╚══════════════════════════════════════════╝\n");
@@ -125,18 +118,25 @@ async function main() {
125
118
  await copyDir(join(PACKAGE_ROOT, dir), destDir);
126
119
  }
127
120
 
128
- const apiKey = await loadApiKey();
129
- if (!apiKey) {
130
- console.error(
131
- "\nError: API key missing. Run setup again to configure it."
132
- );
133
- process.exit(1);
134
- }
135
- await writeMcpConfig(apiKey);
121
+ await writeMcpConfig();
136
122
 
137
123
  console.log("✓ Plugin files copied to ~/.claude/skills/audaxic-memory/");
138
124
  console.log("✓ MCP server configured (memory-mcp.audaxic.com)");
139
125
 
126
+ const directory = displayPath(process.cwd());
127
+ const configureDir = await rl.question(
128
+ `\nConfigure a separate API key for ${directory}? (y/N): `
129
+ );
130
+ if (configureDir.toLowerCase() === "y") {
131
+ const dirKey = await rl.question(`Enter the API key for ${directory}: `);
132
+ if (!dirKey.trim()) {
133
+ console.error("Error: API key cannot be empty.");
134
+ } else {
135
+ await setDirectoryKey(directory, dirKey);
136
+ console.log(`✓ Directory key saved for ${directory}: ${maskKey(dirKey)}`);
137
+ }
138
+ }
139
+
140
140
  console.log("\n╔══════════════════════════════════════════╗");
141
141
  console.log("║ Setup Complete! ║");
142
142
  console.log("╚══════════════════════════════════════════╝\n");
@@ -144,9 +144,9 @@ async function main() {
144
144
  console.log(" • Skill → auto-searches memory for your questions");
145
145
  console.log(" • MCP tools → search_memories / add_memory");
146
146
  console.log(" • Hooks → saves every message immediately (parallel-safe)");
147
+ console.log(" • Directory keys → npx @audaxic/memory-claude key set");
147
148
  console.log("\nThe plugin auto-loads on your next Claude Code session.");
148
- console.log("If the API key prompt doesn't appear, the key from");
149
- console.log("~/.config/audaxic/config.json will be used automatically.\n");
149
+ console.log("The general key is stored in ~/.config/audaxic/config.json.\n");
150
150
  console.log("To uninstall, delete ~/.claude/skills/audaxic-memory/\n");
151
151
  } catch (error) {
152
152
  console.error("\nSetup failed:", error.message);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@audaxic/memory-claude",
3
- "version": "1.1.0",
3
+ "version": "1.2.0",
4
4
  "description": "Claude Code plugin for Audaxic Memory — automatically saves conversation facts and injects semantic context",
5
5
  "type": "module",
6
6
  "bin": {
@@ -13,6 +13,9 @@
13
13
  "scripts",
14
14
  "skills"
15
15
  ],
16
+ "scripts": {
17
+ "test": "node --test test/*.test.mjs"
18
+ },
16
19
  "keywords": [
17
20
  "claude",
18
21
  "claude-code",
@@ -1,9 +1,11 @@
1
- import { readFile } from "node:fs/promises";
2
1
  import { join } from "node:path";
3
2
  import { homedir } from "node:os";
4
- import { saveMessage, drainStale, migrateLegacy } from "./parking.mjs";
3
+ import { setDefaultResultOrder } from "node:dns";
4
+ import { parkMessage, drainStale, migrateLegacy } from "./parking.mjs";
5
+ import { resolveApiKey, resolveGeneralApiKey } from "./config.mjs";
6
+
7
+ setDefaultResultOrder("ipv4first");
5
8
 
6
- const CONFIG_PATH = join(homedir(), ".config", "audaxic", "config.json");
7
9
  const BUFFER_DIR =
8
10
  process.env.CLAUDE_PLUGIN_DATA || join(homedir(), ".claude", "audaxic");
9
11
  const PENDING_DIR = join(BUFFER_DIR, "pending");
@@ -48,15 +50,29 @@ async function main() {
48
50
  process.exit(0);
49
51
  }
50
52
 
51
- const apiKey = await loadApiKey();
53
+ const directory =
54
+ process.env.CLAUDE_PROJECT_DIR || input.cwd || process.cwd();
55
+ const resolution = await resolveApiKey(directory, {
56
+ pluginKey: process.env.CLAUDE_PLUGIN_OPTION_API_TOKEN,
57
+ });
58
+ const apiKey = resolution.key;
52
59
  if (!apiKey) {
53
60
  process.exit(0);
54
61
  }
55
62
 
56
- await migrateLegacy(apiKey, LEGACY_BUFFER_PATH, PENDING_DIR);
63
+ const general = await resolveGeneralApiKey({
64
+ pluginKey: process.env.CLAUDE_PLUGIN_OPTION_API_TOKEN,
65
+ });
66
+
67
+ await migrateLegacy(LEGACY_BUFFER_PATH, PENDING_DIR, {
68
+ apiKey: general.key,
69
+ });
57
70
 
58
- await saveMessage(apiKey, PENDING_DIR, assistantMessage.trim());
59
- await drainStale(apiKey, PENDING_DIR);
71
+ await parkMessage(PENDING_DIR, assistantMessage.trim(), {
72
+ apiKey,
73
+ directory: resolution.displayDirectory,
74
+ });
75
+ await drainStale(general.key, PENDING_DIR, { limit: 3, timeoutMs: 25000 });
60
76
 
61
77
  process.exit(0);
62
78
  } catch {
@@ -0,0 +1,260 @@
1
+ import { readFile, writeFile, mkdir, rename, unlink, realpath } from "node:fs/promises";
2
+ import {
3
+ join,
4
+ resolve,
5
+ dirname,
6
+ relative,
7
+ isAbsolute,
8
+ normalize,
9
+ basename,
10
+ sep,
11
+ } from "node:path";
12
+ import { homedir } from "node:os";
13
+ import { execFile } from "node:child_process";
14
+ import { promisify } from "node:util";
15
+
16
+ const execFileAsync = promisify(execFile);
17
+
18
+ export function getConfigPath() {
19
+ const override = process.env.AUDAXIC_CONFIG;
20
+ if (override && override.trim()) return resolve(override.trim());
21
+ return join(homedir(), ".config", "audaxic", "config.json");
22
+ }
23
+
24
+ export function displayPath(directory) {
25
+ return resolve(directory || process.cwd());
26
+ }
27
+
28
+ export async function canonicalPath(directory) {
29
+ let resolved = displayPath(directory);
30
+ try {
31
+ resolved = await realpath(resolved);
32
+ } catch {}
33
+ resolved = normalize(resolved);
34
+ if (process.platform === "win32") resolved = resolved.toLowerCase();
35
+ return resolved;
36
+ }
37
+
38
+ export async function readConfig() {
39
+ try {
40
+ const raw = await readFile(getConfigPath(), "utf-8");
41
+ const parsed = JSON.parse(raw.replace(/^\uFEFF/, ""));
42
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
43
+ return parsed;
44
+ } catch {
45
+ return {};
46
+ }
47
+ }
48
+
49
+ export async function writeConfig(config) {
50
+ const path = getConfigPath();
51
+ const dir = dirname(path);
52
+ await mkdir(dir, { recursive: true, mode: 0o700 });
53
+ const body = `${JSON.stringify(config, null, 2)}\n`;
54
+ const tmp = `${path}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 10)}`;
55
+ try {
56
+ await writeFile(tmp, body, { mode: 0o600 });
57
+ await rename(tmp, path);
58
+ } catch {
59
+ await unlink(tmp).catch(() => {});
60
+ await writeFile(path, body, { mode: 0o600 });
61
+ }
62
+ }
63
+
64
+ export function getDirectoryEntries(config) {
65
+ const map = config?.directoryKeys;
66
+ if (!map || typeof map !== "object" || Array.isArray(map)) return [];
67
+ return Object.entries(map)
68
+ .filter(
69
+ ([path, key]) =>
70
+ typeof path === "string" &&
71
+ path.trim().length > 0 &&
72
+ typeof key === "string" &&
73
+ key.trim().length > 0
74
+ )
75
+ .map(([path, key]) => ({ path, key: key.trim() }));
76
+ }
77
+
78
+ function isWithin(child, parent) {
79
+ const rel = relative(parent, child);
80
+ return (
81
+ rel === "" ||
82
+ (!isAbsolute(rel) && rel !== ".." && !rel.startsWith(`..${sep}`))
83
+ );
84
+ }
85
+
86
+ async function matchEntries(entries, targetCanonical) {
87
+ let best = null;
88
+ for (const entry of entries) {
89
+ const entryCanonical = await canonicalPath(entry.path);
90
+ if (!isWithin(targetCanonical, entryCanonical)) continue;
91
+ if (!best || entryCanonical.length > best.canonicalPath.length) {
92
+ best = {
93
+ key: entry.key,
94
+ matchedPath: entry.path,
95
+ canonicalPath: entryCanonical,
96
+ };
97
+ }
98
+ }
99
+ return best;
100
+ }
101
+
102
+ async function getMainWorktreePath(directory) {
103
+ try {
104
+ const { stdout } = await execFileAsync(
105
+ "git",
106
+ [
107
+ "-C",
108
+ directory,
109
+ "rev-parse",
110
+ "--path-format=absolute",
111
+ "--git-common-dir",
112
+ ],
113
+ { timeout: 1500, windowsHide: true }
114
+ );
115
+ const common = stdout.trim();
116
+ if (!common) return null;
117
+ const resolved = resolve(common);
118
+ return basename(resolved) === ".git" ? dirname(resolved) : null;
119
+ } catch {
120
+ return null;
121
+ }
122
+ }
123
+
124
+ /**
125
+ * Resolve the API key for a directory.
126
+ *
127
+ * Order: AUDAXIC_API_KEY > nearest directory key > Claude plugin option > general key.
128
+ * A git worktree with no direct match falls back to the main checkout's key.
129
+ */
130
+ export async function resolveApiKey(directory, options = {}) {
131
+ const env = options.env || process.env;
132
+ const display = displayPath(directory);
133
+ const canonical = await canonicalPath(display);
134
+ const base = { directory: canonical, displayDirectory: display };
135
+
136
+ const envKey =
137
+ typeof env.AUDAXIC_API_KEY === "string" ? env.AUDAXIC_API_KEY.trim() : "";
138
+ if (envKey) {
139
+ return { ...base, key: envKey, source: "env", matchedPath: null };
140
+ }
141
+
142
+ const config = options.config || (await readConfig());
143
+ const entries = getDirectoryEntries(config);
144
+
145
+ if (entries.length > 0) {
146
+ const direct = await matchEntries(entries, canonical);
147
+ if (direct) {
148
+ return { ...base, key: direct.key, source: "directory", matchedPath: direct.matchedPath };
149
+ }
150
+
151
+ if (!options.noGit) {
152
+ const mainPath = await getMainWorktreePath(display);
153
+ if (mainPath) {
154
+ const mainCanonical = await canonicalPath(mainPath);
155
+ if (mainCanonical !== canonical) {
156
+ const fallback = await matchEntries(entries, mainCanonical);
157
+ if (fallback) {
158
+ return {
159
+ ...base,
160
+ key: fallback.key,
161
+ source: "worktree",
162
+ matchedPath: fallback.matchedPath,
163
+ };
164
+ }
165
+ }
166
+ }
167
+ }
168
+ }
169
+
170
+ const pluginKey =
171
+ typeof options.pluginKey === "string" ? options.pluginKey.trim() : "";
172
+ if (pluginKey) {
173
+ return { ...base, key: pluginKey, source: "plugin", matchedPath: null };
174
+ }
175
+
176
+ const generalKey =
177
+ typeof config.apiKey === "string" ? config.apiKey.trim() : "";
178
+ if (generalKey) {
179
+ return { ...base, key: generalKey, source: "general", matchedPath: null };
180
+ }
181
+
182
+ return { ...base, key: null, source: "none", matchedPath: null };
183
+ }
184
+
185
+ export function maskKey(key) {
186
+ if (!key || typeof key !== "string") return "(none)";
187
+ const value = key.trim();
188
+ if (value.length <= 12) return "***";
189
+ return `${value.slice(0, 8)}...${value.slice(-4)}`;
190
+ }
191
+
192
+ /**
193
+ * Resolve the general key, ignoring directory mappings. Used only for legacy
194
+ * parked messages captured before per-message keys existed.
195
+ */
196
+ export async function resolveGeneralApiKey(options = {}) {
197
+ const env = options.env || process.env;
198
+ const envKey =
199
+ typeof env.AUDAXIC_API_KEY === "string" ? env.AUDAXIC_API_KEY.trim() : "";
200
+ if (envKey) return { key: envKey, source: "env" };
201
+
202
+ const config = options.config || (await readConfig());
203
+ const pluginKey =
204
+ typeof options.pluginKey === "string" ? options.pluginKey.trim() : "";
205
+ if (pluginKey) return { key: pluginKey, source: "plugin" };
206
+
207
+ const generalKey =
208
+ typeof config.apiKey === "string" ? config.apiKey.trim() : "";
209
+ if (generalKey) return { key: generalKey, source: "general" };
210
+
211
+ return { key: null, source: "none" };
212
+ }
213
+
214
+ export async function setGlobalKey(key) {
215
+ const value = String(key || "").trim();
216
+ if (!value) throw new Error("API key cannot be empty");
217
+ const config = await readConfig();
218
+ config.apiKey = value;
219
+ await writeConfig(config);
220
+ return value;
221
+ }
222
+
223
+ export async function setDirectoryKey(directory, key) {
224
+ const value = String(key || "").trim();
225
+ if (!value) throw new Error("API key cannot be empty");
226
+ const target = displayPath(directory);
227
+ const targetCanonical = await canonicalPath(target);
228
+ const config = await readConfig();
229
+ const next = {};
230
+
231
+ for (const entry of getDirectoryEntries(config)) {
232
+ if ((await canonicalPath(entry.path)) === targetCanonical) continue;
233
+ next[entry.path] = entry.key;
234
+ }
235
+ next[target] = value;
236
+ config.directoryKeys = next;
237
+ await writeConfig(config);
238
+ return { directory: target, key: value };
239
+ }
240
+
241
+ export async function removeDirectoryKey(directory) {
242
+ const target = displayPath(directory);
243
+ const targetCanonical = await canonicalPath(target);
244
+ const config = await readConfig();
245
+ const next = {};
246
+ let removed = null;
247
+
248
+ for (const entry of getDirectoryEntries(config)) {
249
+ if ((await canonicalPath(entry.path)) === targetCanonical) {
250
+ removed = entry;
251
+ continue;
252
+ }
253
+ next[entry.path] = entry.key;
254
+ }
255
+
256
+ if (!removed) return null;
257
+ config.directoryKeys = next;
258
+ await writeConfig(config);
259
+ return removed;
260
+ }
@@ -1,13 +1,13 @@
1
- import { readFile, appendFile, mkdir } from "node:fs/promises";
1
+ import { appendFile, mkdir } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
3
  import { homedir } from "node:os";
4
4
  import { setDefaultResultOrder } from "node:dns";
5
- import { saveMessage, drainStale, migrateLegacy } from "./parking.mjs";
5
+ import { parkMessage, drainStale, migrateLegacy } from "./parking.mjs";
6
+ import { resolveApiKey, resolveGeneralApiKey } from "./config.mjs";
6
7
 
7
8
  setDefaultResultOrder("ipv4first");
8
9
 
9
- const API_BASE = "https://api.memory.audaxic.com";
10
- const CONFIG_PATH = join(homedir(), ".config", "audaxic", "config.json");
10
+ const API_BASE = process.env.AUDAXIC_API_BASE || "https://api.memory.audaxic.com";
11
11
  const BUFFER_DIR =
12
12
  process.env.CLAUDE_PLUGIN_DATA || join(homedir(), ".claude", "audaxic");
13
13
  const PENDING_DIR = join(BUFFER_DIR, "pending");
@@ -35,20 +35,6 @@ async function logFailure(message) {
35
35
  } catch {}
36
36
  }
37
37
 
38
- async function loadApiKey() {
39
- const envKey = process.env.CLAUDE_PLUGIN_OPTION_API_TOKEN;
40
- if (envKey && envKey.trim()) return envKey.trim();
41
-
42
- try {
43
- const raw = await readFile(CONFIG_PATH, "utf-8");
44
- const config = JSON.parse(raw);
45
- if (typeof config.apiKey === "string" && config.apiKey.length > 0) {
46
- return config.apiKey;
47
- }
48
- } catch {}
49
- return null;
50
- }
51
-
52
38
  async function searchOnce(apiKey, query) {
53
39
  const controller = new AbortController();
54
40
  const timeout = setTimeout(() => controller.abort(), SEARCH_TIMEOUT_MS);
@@ -89,11 +75,6 @@ async function searchMemory(apiKey, query) {
89
75
  return [];
90
76
  }
91
77
 
92
- async function saveAndDrain(apiKey, message) {
93
- await saveMessage(apiKey, PENDING_DIR, message);
94
- await drainStale(apiKey, PENDING_DIR);
95
- }
96
-
97
78
  function outputJson(obj) {
98
79
  process.stdout.write(JSON.stringify(obj));
99
80
  }
@@ -108,16 +89,31 @@ async function main() {
108
89
  return;
109
90
  }
110
91
 
111
- const apiKey = await loadApiKey();
92
+ const directory =
93
+ process.env.CLAUDE_PROJECT_DIR || input.cwd || process.cwd();
94
+ const resolution = await resolveApiKey(directory, {
95
+ pluginKey: process.env.CLAUDE_PLUGIN_OPTION_API_TOKEN,
96
+ });
97
+ const apiKey = resolution.key;
112
98
  if (!apiKey) {
113
99
  outputJson({});
114
100
  return;
115
101
  }
116
102
 
117
- await migrateLegacy(apiKey, LEGACY_BUFFER_PATH, PENDING_DIR);
103
+ const general = await resolveGeneralApiKey({
104
+ pluginKey: process.env.CLAUDE_PLUGIN_OPTION_API_TOKEN,
105
+ });
106
+
107
+ await migrateLegacy(LEGACY_BUFFER_PATH, PENDING_DIR, {
108
+ apiKey: general.key,
109
+ });
110
+ await parkMessage(PENDING_DIR, prompt.trim(), {
111
+ apiKey,
112
+ directory: resolution.displayDirectory,
113
+ });
118
114
 
119
115
  const [, searchResult] = await Promise.allSettled([
120
- saveAndDrain(apiKey, prompt.trim()),
116
+ drainStale(general.key, PENDING_DIR, { limit: 1, timeoutMs: 15000 }),
121
117
  searchMemory(apiKey, prompt.trim()),
122
118
  ]);
123
119
 
@@ -0,0 +1,177 @@
1
+ import { createInterface } from "node:readline/promises";
2
+ import { stdin, stdout } from "node:process";
3
+ import {
4
+ displayPath,
5
+ getConfigPath,
6
+ getDirectoryEntries,
7
+ maskKey,
8
+ readConfig,
9
+ removeDirectoryKey,
10
+ resolveApiKey,
11
+ setDirectoryKey,
12
+ setGlobalKey,
13
+ } from "./config.mjs";
14
+
15
+ function parseFlags(args) {
16
+ const flags = { global: false, dir: null, key: null };
17
+ for (let i = 0; i < args.length; i++) {
18
+ const arg = args[i];
19
+ if (arg === "--global") flags.global = true;
20
+ else if (arg === "--dir") flags.dir = args[++i] || null;
21
+ else if (arg.startsWith("--dir=")) flags.dir = arg.slice(6);
22
+ else if (arg === "--key") flags.key = args[++i] || null;
23
+ else if (arg.startsWith("--key=")) flags.key = arg.slice(6);
24
+ else throw new Error(`Unknown option: ${arg}`);
25
+ }
26
+ return flags;
27
+ }
28
+
29
+ function printHelp(packageName) {
30
+ console.log(`\nAudaxic Memory directory keys\n`);
31
+ console.log(`Usage: npx ${packageName} key <command> [options]\n`);
32
+ console.log(`Commands:`);
33
+ console.log(` set [--global] [--dir <path>] [--key <key>] Set a general or directory key`);
34
+ console.log(` list Show configured keys and current resolution`);
35
+ console.log(` resolve [--dir <path>] Show which key applies to a directory`);
36
+ console.log(` remove [--dir <path>] Remove a directory key\n`);
37
+ console.log(`Examples:`);
38
+ console.log(` npx ${packageName} key set --global`);
39
+ console.log(` cd C:\\projeler\\my-project && npx ${packageName} key set`);
40
+ console.log(` npx ${packageName} key resolve\n`);
41
+ }
42
+
43
+ async function promptValue(question) {
44
+ if (!stdin.isTTY) {
45
+ throw new Error("No TTY available. Pass the key with --key.");
46
+ }
47
+ const rl = createInterface({ input: stdin, output: stdout });
48
+ try {
49
+ return await rl.question(question);
50
+ } finally {
51
+ rl.close();
52
+ }
53
+ }
54
+
55
+ function warnKeyFormat(key) {
56
+ if (!key.startsWith("ak_")) {
57
+ console.warn('Warning: API keys typically start with "ak_". Proceeding anyway...');
58
+ }
59
+ }
60
+
61
+ async function keySet(flags) {
62
+ if (flags.global && flags.dir) {
63
+ throw new Error("Use either --global or --dir, not both.");
64
+ }
65
+
66
+ const target = flags.global ? null : displayPath(flags.dir || process.cwd());
67
+ const label = flags.global ? "general" : `directory ${target}`;
68
+ let key = flags.key;
69
+ if (!key) {
70
+ key = await promptValue(`Enter the Audaxic API key for ${label}: `);
71
+ }
72
+ key = String(key || "").trim();
73
+ if (!key) throw new Error("API key cannot be empty");
74
+ warnKeyFormat(key);
75
+
76
+ if (flags.global) {
77
+ await setGlobalKey(key);
78
+ console.log(`✓ General API key saved: ${maskKey(key)}`);
79
+ console.log(` Config: ${getConfigPath()}`);
80
+ return;
81
+ }
82
+
83
+ await setDirectoryKey(target, key);
84
+ console.log(`✓ Directory key saved for ${target}: ${maskKey(key)}`);
85
+ console.log(` Config: ${getConfigPath()}`);
86
+ }
87
+
88
+ async function keyList() {
89
+ const config = await readConfig();
90
+ const general =
91
+ typeof config.apiKey === "string" && config.apiKey.trim()
92
+ ? config.apiKey.trim()
93
+ : null;
94
+ const entries = getDirectoryEntries(config).sort((a, b) =>
95
+ a.path.localeCompare(b.path)
96
+ );
97
+
98
+ console.log(`Config: ${getConfigPath()}`);
99
+ console.log(`General: ${general ? maskKey(general) : "(not set)"}`);
100
+ console.log("Directories:");
101
+ if (entries.length === 0) {
102
+ console.log(" (none)");
103
+ } else {
104
+ for (const entry of entries) {
105
+ console.log(` ${entry.path} ${maskKey(entry.key)}`);
106
+ }
107
+ }
108
+
109
+ const resolution = await resolveApiKey(process.cwd(), {
110
+ pluginKey: process.env.CLAUDE_PLUGIN_OPTION_API_TOKEN,
111
+ });
112
+ console.log(`\nCurrent directory: ${resolution.displayDirectory}`);
113
+ console.log(`Resolved: ${describeResolution(resolution)}`);
114
+ if (process.env.AUDAXIC_API_KEY) {
115
+ console.log(
116
+ "Warning: AUDAXIC_API_KEY is set and overrides directory keys for this process."
117
+ );
118
+ }
119
+ }
120
+
121
+ async function keyResolve(flags) {
122
+ const target = displayPath(flags.dir || process.cwd());
123
+ const resolution = await resolveApiKey(target, {
124
+ pluginKey: process.env.CLAUDE_PLUGIN_OPTION_API_TOKEN,
125
+ });
126
+ console.log(`Directory: ${resolution.displayDirectory}`);
127
+ console.log(`Resolved: ${describeResolution(resolution)}`);
128
+ if (resolution.matchedPath) {
129
+ console.log(`Matched: ${resolution.matchedPath}`);
130
+ }
131
+ if (process.env.AUDAXIC_API_KEY) {
132
+ console.log(
133
+ "Warning: AUDAXIC_API_KEY is set and overrides directory keys for this process."
134
+ );
135
+ }
136
+ }
137
+
138
+ function describeResolution(resolution) {
139
+ if (!resolution.key) return "no API key configured";
140
+ const key = maskKey(resolution.key);
141
+ if (resolution.source === "env") return `environment override (${key})`;
142
+ if (resolution.source === "directory") return `directory key (${key})`;
143
+ if (resolution.source === "worktree") return `git worktree key (${key})`;
144
+ if (resolution.source === "plugin") return `Claude plugin key (${key})`;
145
+ return `general key (${key})`;
146
+ }
147
+
148
+ async function keyRemove(flags) {
149
+ const target = displayPath(flags.dir || process.cwd());
150
+ const removed = await removeDirectoryKey(target);
151
+ if (!removed) {
152
+ console.log(`No directory key found for ${target}`);
153
+ return;
154
+ }
155
+ console.log(`✓ Removed directory key for ${removed.path}`);
156
+ }
157
+
158
+ export async function runKeyCommand(args, options = {}) {
159
+ const packageName = options.packageName || "@audaxic/memory-claude";
160
+ const [command, ...rest] = args;
161
+ try {
162
+ const flags = parseFlags(rest);
163
+ if (command === "set") return await keySet(flags);
164
+ if (command === "list") return await keyList();
165
+ if (command === "resolve") return await keyResolve(flags);
166
+ if (command === "remove") return await keyRemove(flags);
167
+ if (command === "help" || command === "--help" || command === "-h") {
168
+ printHelp(packageName);
169
+ return;
170
+ }
171
+ printHelp(packageName);
172
+ process.exitCode = 1;
173
+ } catch (error) {
174
+ console.error(`Error: ${error.message}`);
175
+ process.exitCode = 1;
176
+ }
177
+ }
@@ -0,0 +1,59 @@
1
+ #!/usr/bin/env node
2
+ import { spawn } from "node:child_process";
3
+ import { resolveApiKey } from "./config.mjs";
4
+
5
+ const MCP_URL =
6
+ process.env.AUDAXIC_MCP_URL || "https://memory-mcp.audaxic.com/mcp";
7
+
8
+ function quote(value) {
9
+ return `"${String(value).replace(/"/g, '\\"')}"`;
10
+ }
11
+
12
+ const directory = process.env.CLAUDE_PROJECT_DIR || process.cwd();
13
+ const resolution = await resolveApiKey(directory, {
14
+ pluginKey: process.env.CLAUDE_PLUGIN_OPTION_API_TOKEN,
15
+ });
16
+
17
+ if (!resolution.key) {
18
+ process.stderr.write(
19
+ `audaxic-memory: no API key configured for ${resolution.displayDirectory}\n`
20
+ );
21
+ process.exit(1);
22
+ }
23
+
24
+ const header = `Authorization: Bearer ${resolution.key}`;
25
+ const args = ["-y", "mcp-remote", MCP_URL, "--header", header];
26
+ const env = { ...process.env };
27
+
28
+ let child;
29
+ if (process.platform === "win32") {
30
+ const command = ["npx", ...args].map(quote).join(" ");
31
+ child = spawn(process.env.ComSpec || "cmd.exe", ["/d", "/s", "/c", command], {
32
+ stdio: "inherit",
33
+ env,
34
+ windowsHide: true,
35
+ });
36
+ } else {
37
+ child = spawn("npx", args, { stdio: "inherit", env });
38
+ }
39
+
40
+ child.on("error", (error) => {
41
+ process.stderr.write(`audaxic-memory: failed to start mcp-remote: ${error.message}\n`);
42
+ process.exit(1);
43
+ });
44
+
45
+ for (const signal of ["SIGINT", "SIGTERM"]) {
46
+ process.on(signal, () => {
47
+ try {
48
+ child.kill(signal);
49
+ } catch {}
50
+ });
51
+ }
52
+
53
+ child.on("exit", (code, signal) => {
54
+ if (signal) {
55
+ process.exit(1);
56
+ return;
57
+ }
58
+ process.exit(code ?? 0);
59
+ });
@@ -9,10 +9,11 @@ import {
9
9
  } from "node:fs/promises";
10
10
  import { join } from "node:path";
11
11
 
12
- const API_BASE = "https://api.memory.audaxic.com";
13
- export const SEND_TIMEOUT_MS = 6000;
12
+ const API_BASE = process.env.AUDAXIC_API_BASE || "https://api.memory.audaxic.com";
13
+ export const SEND_TIMEOUT_MS = 25000;
14
14
  export const DRAIN_STALE_MS = 60000;
15
- export const DRAIN_LIMIT = 2;
15
+ export const CLAIM_STALE_MS = 300000;
16
+ export const DRAIN_LIMIT = 3;
16
17
 
17
18
  function today() {
18
19
  return new Date().toISOString().split("T")[0];
@@ -22,9 +23,9 @@ function randomSuffix() {
22
23
  return Math.random().toString(36).slice(2, 10);
23
24
  }
24
25
 
25
- export async function postAdd(apiKey, messages, date) {
26
+ async function postAdd(apiKey, messages, date, timeoutMs = SEND_TIMEOUT_MS) {
26
27
  const controller = new AbortController();
27
- const timeout = setTimeout(() => controller.abort(), SEND_TIMEOUT_MS);
28
+ const timeout = setTimeout(() => controller.abort(), timeoutMs);
28
29
 
29
30
  try {
30
31
  const response = await fetch(`${API_BASE}/add`, {
@@ -45,7 +46,7 @@ export async function postAdd(apiKey, messages, date) {
45
46
  }
46
47
  }
47
48
 
48
- async function sendParked(apiKey, file) {
49
+ async function sendParked(apiKey, file, timeoutMs) {
49
50
  let payload;
50
51
  try {
51
52
  payload = JSON.parse(await readFile(file, "utf-8"));
@@ -61,54 +62,82 @@ async function sendParked(apiKey, file) {
61
62
  return false;
62
63
  }
63
64
 
64
- const ok = await postAdd(apiKey, [message], payload.date);
65
+ const key =
66
+ (typeof payload?.apiKey === "string" && payload.apiKey.trim()) || apiKey;
67
+ if (!key) return false;
68
+
69
+ const ok = await postAdd(key, [message], payload.date, timeoutMs);
65
70
  if (ok) await unlink(file).catch(() => {});
66
71
  return ok;
67
72
  }
68
73
 
69
- export async function saveMessage(apiKey, pendingDir, message) {
74
+ export async function parkMessage(pendingDir, message, options = {}) {
70
75
  const text = typeof message === "string" ? message.trim() : "";
71
- if (!text) return false;
76
+ if (!text) return null;
77
+
78
+ const payload = { message: text, date: today() };
79
+ if (options.apiKey) payload.apiKey = options.apiKey;
80
+ if (options.directory) payload.directory = options.directory;
72
81
 
73
82
  const file = join(pendingDir, `${Date.now()}-${randomSuffix()}.json`);
74
83
  try {
75
84
  await mkdir(pendingDir, { recursive: true });
76
- await writeFile(file, JSON.stringify({ message: text, date: today() }), {
77
- mode: 0o600,
78
- });
85
+ await writeFile(file, JSON.stringify(payload), { mode: 0o600 });
86
+ return file;
79
87
  } catch {
80
- return false;
88
+ return null;
81
89
  }
82
-
83
- return sendParked(apiKey, file);
84
90
  }
85
91
 
86
- export async function drainStale(apiKey, pendingDir, limit = DRAIN_LIMIT) {
92
+ async function healClaimOrphans(pendingDir) {
87
93
  const entries = await readdir(pendingDir).catch(() => []);
94
+ for (const entry of entries) {
95
+ const idx = entry.indexOf(".json.claim-");
96
+ if (idx === -1) continue;
97
+ const file = join(pendingDir, entry);
98
+ const info = await stat(file).catch(() => null);
99
+ if (!info || Date.now() - info.mtimeMs < CLAIM_STALE_MS) continue;
100
+ const base = join(pendingDir, entry.slice(0, idx + 5));
101
+ await rename(file, base).catch(() => {});
102
+ }
103
+ }
88
104
 
89
- let drained = 0;
105
+ export async function drainStale(
106
+ apiKey,
107
+ pendingDir,
108
+ options = {}
109
+ ) {
110
+ const limit = options.limit ?? DRAIN_LIMIT;
111
+ const timeoutMs = options.timeoutMs ?? SEND_TIMEOUT_MS;
112
+
113
+ await healClaimOrphans(pendingDir);
114
+
115
+ const entries = await readdir(pendingDir).catch(() => []);
116
+ const stale = [];
90
117
  for (const entry of entries) {
91
- if (drained >= limit) break;
118
+ if (stale.length >= limit) break;
92
119
  if (!entry.endsWith(".json")) continue;
93
-
94
120
  const file = join(pendingDir, entry);
95
121
  const info = await stat(file).catch(() => null);
96
122
  if (!info || Date.now() - info.mtimeMs < DRAIN_STALE_MS) continue;
97
-
98
- const claim = `${file}.claim-${randomSuffix()}`;
99
- try {
100
- await rename(file, claim);
101
- } catch {
102
- continue;
103
- }
104
-
105
- const ok = await sendParked(apiKey, claim);
106
- if (!ok) await rename(claim, file).catch(() => {});
107
- drained++;
123
+ stale.push(file);
108
124
  }
125
+
126
+ await Promise.all(
127
+ stale.map(async (file) => {
128
+ const claim = `${file}.claim-${randomSuffix()}`;
129
+ try {
130
+ await rename(file, claim);
131
+ } catch {
132
+ return;
133
+ }
134
+ const ok = await sendParked(apiKey, claim, timeoutMs);
135
+ if (!ok) await rename(claim, file).catch(() => {});
136
+ })
137
+ );
109
138
  }
110
139
 
111
- export async function migrateLegacy(apiKey, legacyPath, pendingDir) {
140
+ export async function migrateLegacy(legacyPath, pendingDir, options = {}) {
112
141
  try {
113
142
  const raw = await readFile(legacyPath, "utf-8");
114
143
  const parsed = JSON.parse(raw);
@@ -117,17 +146,13 @@ export async function migrateLegacy(apiKey, legacyPath, pendingDir) {
117
146
  : [];
118
147
 
119
148
  if (messages.length > 0) {
120
- const ok = await postAdd(apiKey, messages, today());
121
- if (!ok) {
122
- await mkdir(pendingDir, { recursive: true });
123
- for (const message of messages) {
124
- const file = join(pendingDir, `${Date.now()}-${randomSuffix()}.json`);
125
- await writeFile(
126
- file,
127
- JSON.stringify({ message, date: today() }),
128
- { mode: 0o600 }
129
- );
130
- }
149
+ await mkdir(pendingDir, { recursive: true });
150
+ for (const message of messages) {
151
+ const payload = { message, date: today() };
152
+ if (options.apiKey) payload.apiKey = options.apiKey;
153
+ if (options.directory) payload.directory = options.directory;
154
+ const file = join(pendingDir, `${Date.now()}-${randomSuffix()}.json`);
155
+ await writeFile(file, JSON.stringify(payload), { mode: 0o600 });
131
156
  }
132
157
  }
133
158