memoryrouter-claude 1.0.0 → 2.0.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/CHANGELOG.md +30 -0
- package/README.md +164 -64
- package/bin/cli.js +240 -158
- package/lib/api.js +10 -17
- package/lib/config.js +105 -20
- package/lib/hook-runner.js +365 -134
- package/lib/project.js +153 -0
- package/lib/settings.js +56 -58
- package/lib/transcript.js +233 -43
- package/package.json +9 -4
package/bin/cli.js
CHANGED
|
@@ -1,42 +1,65 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
'use strict';
|
|
3
|
-
// MemoryRouter CLI for Claude Code.
|
|
4
|
-
// Commands: init, status, off|uninstall, hook <kind>
|
|
5
3
|
|
|
4
|
+
const fs = require('fs');
|
|
6
5
|
const path = require('path');
|
|
7
6
|
const readline = require('readline');
|
|
7
|
+
const { spawnSync } = require('child_process');
|
|
8
8
|
const {
|
|
9
|
+
CONFIG_VERSION,
|
|
10
|
+
CONFIG_DIR,
|
|
11
|
+
CONFIG_PATH,
|
|
12
|
+
STATE_DIR,
|
|
9
13
|
loadConfig,
|
|
10
14
|
saveConfig,
|
|
15
|
+
migrateConfig,
|
|
11
16
|
getApiKey,
|
|
12
|
-
|
|
17
|
+
configPermissions,
|
|
18
|
+
pruneState,
|
|
13
19
|
} = require('../lib/config');
|
|
14
20
|
const api = require('../lib/api');
|
|
15
21
|
const settingsLib = require('../lib/settings');
|
|
22
|
+
const { deriveProjectIdentity } = require('../lib/project');
|
|
16
23
|
const { runHook } = require('../lib/hook-runner');
|
|
17
24
|
|
|
18
|
-
const
|
|
25
|
+
const PKG = require('../package.json');
|
|
26
|
+
const VERSION = PKG.version;
|
|
27
|
+
const MCP_URL = 'https://mcp.memoryrouter.ai/mcp';
|
|
19
28
|
|
|
20
29
|
const HELP = `
|
|
21
|
-
|
|
30
|
+
${PKG.name} v${VERSION} — deterministic memory for Claude Code
|
|
22
31
|
|
|
23
32
|
Usage:
|
|
24
|
-
npx memoryrouter-claude init [--key mk_xxx] [--user
|
|
25
|
-
Install memory hooks
|
|
26
|
-
--
|
|
27
|
-
--project
|
|
28
|
-
--user
|
|
29
|
-
--
|
|
33
|
+
npx memoryrouter-claude init [--key mk_xxx] [--local|--project|--user] [--yes]
|
|
34
|
+
Install or upgrade automatic memory hooks without replacing user settings.
|
|
35
|
+
--local ./.claude/settings.local.json (private project install)
|
|
36
|
+
--project ./.claude/settings.json (team/shareable; default)
|
|
37
|
+
--user ~/.claude/settings.json (all projects)
|
|
38
|
+
--global Explicitly use personal/global memory instead of project memory
|
|
39
|
+
--include-global Recall project memory plus personal/global memory
|
|
40
|
+
--capture-subagents Capture subagent transcripts (off by default)
|
|
41
|
+
|
|
42
|
+
npx memoryrouter-claude doctor
|
|
43
|
+
Diagnose config migration, permissions, hooks, project scope, pending capture,
|
|
44
|
+
API reachability, and optional MCP configuration.
|
|
30
45
|
|
|
31
46
|
npx memoryrouter-claude status
|
|
32
|
-
Show key validity
|
|
47
|
+
Show key validity, vault stats, and deterministic project identity.
|
|
48
|
+
|
|
49
|
+
npx memoryrouter-claude off [--local|--project|--user] [--purge]
|
|
50
|
+
Remove only MemoryRouter hooks. --purge also deletes private local config/state.
|
|
51
|
+
Alias: uninstall
|
|
33
52
|
|
|
34
|
-
npx memoryrouter-claude
|
|
35
|
-
|
|
36
|
-
|
|
53
|
+
npx memoryrouter-claude mcp <install|status|remove> [--local|--project|--user]
|
|
54
|
+
Configure the OAuth remote MCP server as the manual recall/remember/control
|
|
55
|
+
surface. Hooks remain the automatic retrieval/capture engine.
|
|
37
56
|
|
|
38
|
-
npx memoryrouter-claude hook <
|
|
39
|
-
Internal
|
|
57
|
+
npx memoryrouter-claude hook <kind>
|
|
58
|
+
Internal Claude Code hook entrypoint. Always exits 0.
|
|
59
|
+
|
|
60
|
+
Environment:
|
|
61
|
+
MEMORYROUTER_API_KEY, MEMORYROUTER_PROJECT_ID, MEMORYROUTER_DISABLE=1,
|
|
62
|
+
MEMORYROUTER_API_BASE, MEMORYROUTER_DEBUG=1
|
|
40
63
|
|
|
41
64
|
Docs: https://memoryrouter.ai/claude-code
|
|
42
65
|
`;
|
|
@@ -44,203 +67,262 @@ Docs: https://memoryrouter.ai/claude-code
|
|
|
44
67
|
function parseArgs(argv) {
|
|
45
68
|
const args = { _: [] };
|
|
46
69
|
for (let i = 0; i < argv.length; i++) {
|
|
47
|
-
const
|
|
48
|
-
if (
|
|
49
|
-
else if (
|
|
50
|
-
else if (
|
|
51
|
-
else if (
|
|
52
|
-
else if (
|
|
53
|
-
else if (
|
|
54
|
-
else if (
|
|
55
|
-
else args.
|
|
70
|
+
const value = argv[i];
|
|
71
|
+
if (value === '--key') args.key = argv[++i];
|
|
72
|
+
else if (value === '--user') args.scope = 'user';
|
|
73
|
+
else if (value === '--project') args.scope = 'project';
|
|
74
|
+
else if (value === '--local') args.scope = 'local';
|
|
75
|
+
else if (value === '--global') args.global = true;
|
|
76
|
+
else if (value === '--include-global') args.includeGlobal = true;
|
|
77
|
+
else if (value === '--capture-subagents') args.captureSubagents = true;
|
|
78
|
+
else if (value === '--yes' || value === '-y') args.yes = true;
|
|
79
|
+
else if (value === '--purge') args.purge = true;
|
|
80
|
+
else if (value === '--final') args.final = true;
|
|
81
|
+
else if (value === '--help' || value === '-h') args.help = true;
|
|
82
|
+
else if (value === '--version' || value === '-v') args.version = true;
|
|
83
|
+
else args._.push(value);
|
|
56
84
|
}
|
|
57
85
|
return args;
|
|
58
86
|
}
|
|
59
87
|
|
|
60
88
|
function ask(question) {
|
|
61
89
|
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
62
|
-
return new Promise((resolve) =>
|
|
63
|
-
rl.
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
}),
|
|
67
|
-
);
|
|
90
|
+
return new Promise((resolve) => rl.question(question, (answer) => {
|
|
91
|
+
rl.close();
|
|
92
|
+
resolve(answer.trim());
|
|
93
|
+
}));
|
|
68
94
|
}
|
|
69
95
|
|
|
70
|
-
// Resolve the command Claude Code should run for our hooks.
|
|
71
|
-
// Prefer this CLI's absolute path (fast cold-start). BUT if we're executing
|
|
72
|
-
// out of the npx ephemeral cache (~/.npm/_npx/...), that path can vanish on
|
|
73
|
-
// cache prune — fall back to `npx -y memoryrouter-claude` which self-heals.
|
|
74
96
|
function resolveBin() {
|
|
75
97
|
const self = path.resolve(__dirname, 'cli.js');
|
|
76
|
-
if (self.includes(`${path.sep}_npx${path.sep}`))
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
return
|
|
98
|
+
if (self.includes(`${path.sep}_npx${path.sep}`)) return 'npx -y memoryrouter-claude';
|
|
99
|
+
return `"${process.execPath}" "${self}"`;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function maskKey(key) {
|
|
103
|
+
return key && key.length > 10 ? `${key.slice(0, 6)}…${key.slice(-4)}` : 'configured';
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
async function validateKey(key, timeoutMs = 10000) {
|
|
107
|
+
const res = await api.stats(key, { timeoutMs });
|
|
108
|
+
if (!res.ok) throw new Error(`key invalid or API error (HTTP ${res.status})`);
|
|
109
|
+
return res.data || {};
|
|
82
110
|
}
|
|
83
111
|
|
|
84
112
|
async function cmdInit(args) {
|
|
85
|
-
console.log(
|
|
113
|
+
console.log('\n MemoryRouter × Claude Code installer / upgrader\n');
|
|
114
|
+
let existing;
|
|
115
|
+
try { existing = loadConfig({ strict: true, migrate: false }); }
|
|
116
|
+
catch (err) { throw new Error(`${err.message}. Existing config was not modified.`); }
|
|
117
|
+
const migration = migrateConfig(existing);
|
|
118
|
+
const cfg = migration.config;
|
|
86
119
|
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
if (!key
|
|
90
|
-
key = await ask(' Memory Key (mk_...): ');
|
|
91
|
-
}
|
|
92
|
-
if (!key || !/^mk[-_]/.test(key)) {
|
|
93
|
-
console.error('\n ✗ A Memory Key (mk_...) is required.');
|
|
94
|
-
console.error(' Get one free at https://app.memoryrouter.ai\n');
|
|
95
|
-
process.exit(1);
|
|
96
|
-
}
|
|
120
|
+
let key = args.key || process.env.MEMORYROUTER_API_KEY || cfg.apiKey || null;
|
|
121
|
+
if (!key && !args.yes) key = await ask(' Memory Key (mk_...): ');
|
|
122
|
+
if (!key || !/^mk[-_]/.test(key)) throw new Error('A Memory Key (mk_...) is required. Get one at https://app.memoryrouter.ai');
|
|
97
123
|
|
|
98
|
-
// 2) Validate against the API
|
|
99
124
|
process.stdout.write(' Validating key… ');
|
|
100
|
-
let
|
|
101
|
-
try {
|
|
102
|
-
|
|
103
|
-
}
|
|
104
|
-
console.error(`network error (${e.message})`);
|
|
105
|
-
process.exit(1);
|
|
106
|
-
}
|
|
107
|
-
if (!statsRes.ok) {
|
|
108
|
-
console.error(`invalid (HTTP ${statsRes.status})`);
|
|
109
|
-
if (statsRes.data && statsRes.data.error) console.error(` ${statsRes.data.error}`);
|
|
110
|
-
process.exit(1);
|
|
111
|
-
}
|
|
112
|
-
const s = statsRes.data || {};
|
|
113
|
-
const vectors = s.totalVectors ?? s.total_vectors ?? 0;
|
|
114
|
-
console.log(`✓ valid (${vectors} memories in vault)`);
|
|
125
|
+
let stats;
|
|
126
|
+
try { stats = await validateKey(key); }
|
|
127
|
+
catch (err) { console.error('failed'); throw err; }
|
|
128
|
+
console.log(`✓ valid (${stats.totalVectors ?? stats.total_vectors ?? 0} memories in vault)`);
|
|
115
129
|
|
|
116
|
-
// 3) Store key privately (0600), NOT in Claude settings
|
|
117
|
-
const cfg = loadConfig();
|
|
118
|
-
cfg.apiKey = key;
|
|
119
|
-
saveConfig(cfg);
|
|
120
|
-
console.log(` Key saved to ${CONFIG_PATH} (0600)`);
|
|
121
|
-
|
|
122
|
-
// 4) Choose settings scope
|
|
123
130
|
let scope = args.scope;
|
|
124
131
|
if (!scope && !args.yes) {
|
|
125
|
-
const
|
|
126
|
-
scope =
|
|
132
|
+
const answer = await ask(' Scope: [1] project, [2] local/private project, [3] user/all projects? [1]: ');
|
|
133
|
+
scope = answer === '2' ? 'local' : answer === '3' ? 'user' : 'project';
|
|
127
134
|
}
|
|
128
135
|
if (!scope) scope = 'project';
|
|
129
136
|
|
|
137
|
+
cfg.apiKey = key;
|
|
138
|
+
if (args.global) cfg.memoryScope = 'global';
|
|
139
|
+
if (args.includeGlobal) cfg.includeGlobal = true;
|
|
140
|
+
if (args.captureSubagents) cfg.captureSubagents = true;
|
|
141
|
+
cfg.lastInstalledVersion = VERSION;
|
|
142
|
+
cfg.lastInstalledAt = new Date().toISOString();
|
|
130
143
|
const file = settingsLib.settingsPathFor(scope, process.cwd());
|
|
144
|
+
cfg.installations = [...new Set([...(Array.isArray(cfg.installations) ? cfg.installations : []), file])];
|
|
145
|
+
saveConfig(cfg);
|
|
131
146
|
|
|
132
|
-
|
|
133
|
-
const
|
|
134
|
-
|
|
135
|
-
settingsLib.installHooks(file, bin);
|
|
136
|
-
} catch (e) {
|
|
137
|
-
console.error(`\n ✗ ${e.message}\n`);
|
|
138
|
-
process.exit(1);
|
|
139
|
-
}
|
|
147
|
+
settingsLib.installHooks(file, resolveBin());
|
|
148
|
+
const project = deriveProjectIdentity({ cwd: process.cwd() }, cfg);
|
|
149
|
+
console.log(` ${migration.changed ? `Config migrated v${migration.fromVersion} → v${CONFIG_VERSION}; ` : ''}key saved → ${CONFIG_PATH} (0600)`);
|
|
140
150
|
console.log(` Hooks installed → ${file}`);
|
|
151
|
+
console.log(` Memory scope → ${project.memoryScope}${project.includeGlobal ? ' + global recall' : ''} (${project.id}, ${project.source})`);
|
|
141
152
|
console.log(`
|
|
142
|
-
|
|
143
|
-
SessionStart
|
|
144
|
-
UserPromptSubmit
|
|
145
|
-
Stop
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
153
|
+
Automatic engine:
|
|
154
|
+
SessionStart asynchronous project-vault warmup
|
|
155
|
+
UserPromptSubmit project-scoped semantic recall
|
|
156
|
+
Stop crash-safe full-turn transcript capture
|
|
157
|
+
StopFailure recovery flush after API failures
|
|
158
|
+
PreCompact lossless flush before compaction
|
|
159
|
+
PostCompact durable compaction-summary capture
|
|
160
|
+
SessionStart re-injection after compact/resume/fork
|
|
161
|
+
SubagentStop optional capture (disabled by default)
|
|
162
|
+
SessionEnd final checkpointed flush
|
|
163
|
+
|
|
164
|
+
✓ Installed. Restart Claude Code or start a new session.
|
|
165
|
+
Run \`npx memoryrouter-claude doctor\` to verify the complete setup.
|
|
166
|
+
Optional manual tools: \`npx memoryrouter-claude mcp install\` then
|
|
167
|
+
\`claude mcp login memoryrouter\`.
|
|
151
168
|
`);
|
|
152
169
|
}
|
|
153
170
|
|
|
154
171
|
async function cmdStatus() {
|
|
155
172
|
const key = getApiKey();
|
|
156
|
-
if (!key)
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
}
|
|
160
|
-
let res;
|
|
161
|
-
try {
|
|
162
|
-
res = await api.stats(key);
|
|
163
|
-
} catch (e) {
|
|
164
|
-
console.error(` ✗ Network error: ${e.message}`);
|
|
165
|
-
process.exit(1);
|
|
166
|
-
}
|
|
167
|
-
if (!res.ok) {
|
|
168
|
-
console.error(` ✗ Key invalid or API error (HTTP ${res.status})`);
|
|
169
|
-
process.exit(1);
|
|
170
|
-
}
|
|
171
|
-
const s = res.data || {};
|
|
172
|
-
const masked = key.slice(0, 6) + '…' + key.slice(-4);
|
|
173
|
+
if (!key) throw new Error('No Memory Key configured. Run: npx memoryrouter-claude init');
|
|
174
|
+
const stats = await validateKey(key);
|
|
175
|
+
const cfg = loadConfig();
|
|
176
|
+
const project = deriveProjectIdentity({ cwd: process.cwd() }, cfg);
|
|
173
177
|
console.log(`
|
|
174
178
|
MemoryRouter status
|
|
175
179
|
───────────────────
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
180
|
+
Version: ${VERSION}
|
|
181
|
+
Config: v${cfg.configVersion}
|
|
182
|
+
Key: ${maskKey(key)} ✓ valid
|
|
183
|
+
Scope: ${project.memoryScope}${project.includeGlobal ? ' + global recall' : ''}
|
|
184
|
+
Project: ${project.id} (${project.source})
|
|
185
|
+
Memories: ${stats.totalVectors ?? stats.total_vectors ?? '?'} vectors
|
|
186
|
+
Tokens: ${stats.totalTokens ?? stats.total_tokens ?? '?'}
|
|
187
|
+
Storage: ${stats.storage ?? '?'}
|
|
182
188
|
`);
|
|
183
189
|
}
|
|
184
190
|
|
|
191
|
+
function inspectState() {
|
|
192
|
+
const report = { files: 0, pending: 0, blocked: 0 };
|
|
193
|
+
try {
|
|
194
|
+
for (const name of fs.readdirSync(STATE_DIR)) {
|
|
195
|
+
if (!name.endsWith('.json')) continue;
|
|
196
|
+
report.files++;
|
|
197
|
+
try {
|
|
198
|
+
const state = JSON.parse(fs.readFileSync(path.join(STATE_DIR, name), 'utf8'));
|
|
199
|
+
if (state.pendingCapture) report.pending++;
|
|
200
|
+
if (state.blockedOffset !== undefined) report.blocked++;
|
|
201
|
+
} catch { report.blocked++; }
|
|
202
|
+
}
|
|
203
|
+
} catch { /* absent */ }
|
|
204
|
+
return report;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function claudeMcp(args, timeout = 8000) {
|
|
208
|
+
return spawnSync('claude', ['mcp', ...args], { encoding: 'utf8', timeout });
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
async function cmdDoctor() {
|
|
212
|
+
const checks = [];
|
|
213
|
+
let cfg;
|
|
214
|
+
try {
|
|
215
|
+
const raw = loadConfig({ strict: true, migrate: false });
|
|
216
|
+
const migration = migrateConfig(raw);
|
|
217
|
+
cfg = migration.config;
|
|
218
|
+
checks.push({ ok: !migration.changed, name: 'Config schema', detail: migration.changed ? `upgrade available v${migration.fromVersion} → v${CONFIG_VERSION} (run init)` : `v${CONFIG_VERSION}` });
|
|
219
|
+
} catch (err) {
|
|
220
|
+
checks.push({ ok: false, name: 'Config schema', detail: err.message });
|
|
221
|
+
cfg = {};
|
|
222
|
+
}
|
|
223
|
+
const perms = configPermissions();
|
|
224
|
+
checks.push({ ok: perms === null || (perms & 0o077) === 0, name: 'Credential permissions', detail: perms === null ? 'config not created' : `mode ${perms.toString(8)}${(perms & 0o077) ? ' (expected 600)' : ''}` });
|
|
225
|
+
|
|
226
|
+
const project = deriveProjectIdentity({ cwd: process.cwd() }, cfg);
|
|
227
|
+
checks.push({ ok: true, name: 'Project identity', detail: `${project.id} via ${project.source}; ${project.memoryScope}${project.includeGlobal ? ' + global' : ''}` });
|
|
228
|
+
|
|
229
|
+
let hookCount = 0;
|
|
230
|
+
for (const scope of ['local', 'project', 'user']) {
|
|
231
|
+
const diagnostic = settingsLib.hookDiagnostics(settingsLib.settingsPathFor(scope, process.cwd()));
|
|
232
|
+
hookCount += diagnostic.owned;
|
|
233
|
+
checks.push({ ok: diagnostic.valid, name: `${scope} settings`, detail: diagnostic.valid ? `${diagnostic.owned} MemoryRouter hooks` : diagnostic.error });
|
|
234
|
+
}
|
|
235
|
+
checks.push({ ok: hookCount > 0, name: 'Hook installation', detail: `${hookCount} owned handlers found` });
|
|
236
|
+
|
|
237
|
+
const state = inspectState();
|
|
238
|
+
checks.push({ ok: state.blocked === 0, name: 'Capture checkpoints', detail: `${state.files} sessions; ${state.pending} retry pending; ${state.blocked} blocked/corrupt` });
|
|
239
|
+
const pruned = pruneState(cfg.stateTtlDays);
|
|
240
|
+
checks.push({ ok: true, name: 'State retention', detail: `${pruned.kept} kept, ${pruned.removed} stale pruned (${pruned.ttlDays}d)` });
|
|
241
|
+
|
|
242
|
+
const key = getApiKey();
|
|
243
|
+
if (!key) checks.push({ ok: false, name: 'API key', detail: 'not configured' });
|
|
244
|
+
else {
|
|
245
|
+
try {
|
|
246
|
+
const stats = await validateKey(key, 5000);
|
|
247
|
+
checks.push({ ok: true, name: 'API reachability', detail: `${maskKey(key)}; ${stats.totalVectors ?? stats.total_vectors ?? '?'} vectors` });
|
|
248
|
+
} catch (err) { checks.push({ ok: false, name: 'API reachability', detail: err.message }); }
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
const mcp = claudeMcp(['get', 'memoryrouter'], 5000);
|
|
252
|
+
if (mcp.error && mcp.error.code === 'ENOENT') checks.push({ ok: true, name: 'Manual MCP surface', detail: 'Claude CLI unavailable (optional)' });
|
|
253
|
+
else checks.push({ ok: mcp.status === 0, name: 'Manual MCP surface', detail: mcp.status === 0 ? 'configured; use /mcp to authenticate/check connection' : 'optional; run `memoryrouter-claude mcp install`' });
|
|
254
|
+
|
|
255
|
+
console.log('\n MemoryRouter doctor\n ─────────────────────────────────────────────────────────────');
|
|
256
|
+
for (const check of checks) console.log(` ${check.ok ? '✓' : '✗'} ${check.name}: ${check.detail}`);
|
|
257
|
+
const failures = checks.filter((c) => !c.ok && c.name !== 'Manual MCP surface');
|
|
258
|
+
console.log(failures.length ? `\n ${failures.length} required check(s) need attention.\n` : '\n ✓ Automatic memory integration is healthy.\n');
|
|
259
|
+
if (failures.length) process.exitCode = 1;
|
|
260
|
+
}
|
|
261
|
+
|
|
185
262
|
async function cmdOff(args) {
|
|
186
|
-
const scopes = args.scope ? [args.scope] : ['project', 'user'];
|
|
187
|
-
let
|
|
263
|
+
const scopes = args.scope ? [args.scope] : ['local', 'project', 'user'];
|
|
264
|
+
let removed = 0;
|
|
188
265
|
for (const scope of scopes) {
|
|
189
266
|
const file = settingsLib.settingsPathFor(scope, process.cwd());
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
267
|
+
try {
|
|
268
|
+
if (settingsLib.uninstallHooks(file) !== null) {
|
|
269
|
+
console.log(` Removed MemoryRouter hooks from ${file}`);
|
|
270
|
+
removed++;
|
|
271
|
+
}
|
|
272
|
+
} catch (err) {
|
|
273
|
+
throw new Error(`${err.message}. No changes were made to that settings file.`);
|
|
194
274
|
}
|
|
195
275
|
}
|
|
196
|
-
if (!
|
|
197
|
-
|
|
276
|
+
if (!removed) console.log(' No MemoryRouter hooks found in selected scopes.');
|
|
277
|
+
if (args.purge) {
|
|
278
|
+
fs.rmSync(CONFIG_DIR, { recursive: true, force: true });
|
|
279
|
+
console.log(` Deleted private MemoryRouter config/state: ${CONFIG_DIR}`);
|
|
280
|
+
} else console.log(` Memory Key retained in ${CONFIG_PATH}. Add --purge to remove it and local state.`);
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
async function cmdMcp(args) {
|
|
284
|
+
const action = args._[1] || 'status';
|
|
285
|
+
const scope = args.scope || 'local';
|
|
286
|
+
let result;
|
|
287
|
+
if (action === 'install') {
|
|
288
|
+
result = claudeMcp(['add', '--transport', 'http', '--scope', scope, 'memoryrouter', MCP_URL], 15000);
|
|
289
|
+
if (result.error) throw new Error(`Could not run Claude CLI: ${result.error.message}`);
|
|
290
|
+
if (result.status !== 0 && !`${result.stdout}${result.stderr}`.includes('already exists')) throw new Error((result.stderr || result.stdout || 'MCP install failed').trim());
|
|
291
|
+
console.log(` MemoryRouter MCP configured at ${scope} scope (${MCP_URL}).`);
|
|
292
|
+
console.log(' Next: claude mcp login memoryrouter (or open /mcp inside Claude Code)');
|
|
293
|
+
} else if (action === 'remove') {
|
|
294
|
+
result = claudeMcp(['remove', '--scope', scope, 'memoryrouter']);
|
|
295
|
+
if (result.error || result.status !== 0) throw new Error((result.error && result.error.message) || (result.stderr || 'MCP remove failed').trim());
|
|
296
|
+
console.log(' Removed the manual MemoryRouter MCP configuration. Automatic hooks are unchanged.');
|
|
297
|
+
} else if (action === 'status') {
|
|
298
|
+
result = claudeMcp(['get', 'memoryrouter']);
|
|
299
|
+
if (result.error) throw new Error(`Could not run Claude CLI: ${result.error.message}`);
|
|
300
|
+
process.stdout.write(result.stdout || result.stderr || 'MemoryRouter MCP is not configured.\n');
|
|
301
|
+
} else throw new Error(`Unknown mcp action: ${action}`);
|
|
198
302
|
}
|
|
199
303
|
|
|
200
304
|
async function main() {
|
|
201
305
|
const args = parseArgs(process.argv.slice(2));
|
|
202
306
|
const cmd = args._[0];
|
|
203
|
-
|
|
204
|
-
if (args.
|
|
205
|
-
console.log(VERSION);
|
|
206
|
-
return;
|
|
207
|
-
}
|
|
208
|
-
if (!cmd || args.help) {
|
|
209
|
-
// `memoryrouter hook X --help` should still show help, fine.
|
|
210
|
-
if (cmd === 'hook' && !args.help) {
|
|
211
|
-
// fallthrough to hook
|
|
212
|
-
} else {
|
|
213
|
-
console.log(HELP);
|
|
214
|
-
return;
|
|
215
|
-
}
|
|
216
|
-
}
|
|
217
|
-
|
|
307
|
+
if (args.version) return console.log(VERSION);
|
|
308
|
+
if (!cmd || args.help) return console.log(HELP);
|
|
218
309
|
switch (cmd) {
|
|
219
|
-
case 'init':
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
case 'status':
|
|
223
|
-
await cmdStatus();
|
|
224
|
-
break;
|
|
310
|
+
case 'init': return cmdInit(args);
|
|
311
|
+
case 'status': return cmdStatus();
|
|
312
|
+
case 'doctor': return cmdDoctor();
|
|
225
313
|
case 'off':
|
|
226
|
-
case 'uninstall':
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
await runHook(args._[1]);
|
|
231
|
-
break;
|
|
232
|
-
default:
|
|
233
|
-
console.log(HELP);
|
|
234
|
-
process.exit(cmd ? 1 : 0);
|
|
314
|
+
case 'uninstall': return cmdOff(args);
|
|
315
|
+
case 'mcp': return cmdMcp(args);
|
|
316
|
+
case 'hook': return runHook(args._[1]);
|
|
317
|
+
default: console.log(HELP); process.exitCode = 1;
|
|
235
318
|
}
|
|
236
319
|
}
|
|
237
320
|
|
|
238
321
|
main().catch((err) => {
|
|
239
|
-
// hook subcommand must never fail; others may report
|
|
240
322
|
if (process.argv[2] === 'hook') {
|
|
241
323
|
if (process.env.MEMORYROUTER_DEBUG) console.error('[memoryrouter]', err);
|
|
242
324
|
process.exit(0);
|
|
243
325
|
}
|
|
244
|
-
console.error(
|
|
326
|
+
console.error(` ✗ ${err && err.message}`);
|
|
245
327
|
process.exit(1);
|
|
246
328
|
});
|
package/lib/api.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
'use strict';
|
|
2
|
-
// Minimal MemoryRouter API client. Node 18+ built-in fetch. No
|
|
2
|
+
// Minimal MemoryRouter API client. Node 18+ built-in fetch. No dependencies.
|
|
3
3
|
|
|
4
4
|
const { API_BASE } = require('./config');
|
|
5
5
|
|
|
@@ -7,7 +7,7 @@ function debug(...args) {
|
|
|
7
7
|
if (process.env.MEMORYROUTER_DEBUG) console.error('[memoryrouter]', ...args);
|
|
8
8
|
}
|
|
9
9
|
|
|
10
|
-
async function request(method, endpoint, { key, body, timeoutMs = 8000 } = {}) {
|
|
10
|
+
async function request(method, endpoint, { key, body, timeoutMs = 8000, headers = {} } = {}) {
|
|
11
11
|
const ctrl = new AbortController();
|
|
12
12
|
const timer = setTimeout(() => ctrl.abort(), timeoutMs);
|
|
13
13
|
try {
|
|
@@ -16,49 +16,42 @@ async function request(method, endpoint, { key, body, timeoutMs = 8000 } = {}) {
|
|
|
16
16
|
headers: {
|
|
17
17
|
Authorization: `Bearer ${key}`,
|
|
18
18
|
'Content-Type': 'application/json',
|
|
19
|
-
'User-Agent': 'memoryrouter-claude
|
|
19
|
+
'User-Agent': 'memoryrouter-claude/' + require('./../package.json').version,
|
|
20
|
+
...headers,
|
|
20
21
|
},
|
|
21
22
|
body: body === undefined ? undefined : JSON.stringify(body),
|
|
22
23
|
signal: ctrl.signal,
|
|
23
24
|
});
|
|
24
25
|
let data = null;
|
|
25
|
-
try {
|
|
26
|
-
data = await res.json();
|
|
27
|
-
} catch {
|
|
28
|
-
/* non-JSON body */
|
|
29
|
-
}
|
|
26
|
+
try { data = await res.json(); } catch { /* non-JSON body */ }
|
|
30
27
|
return { ok: res.ok, status: res.status, data };
|
|
31
28
|
} finally {
|
|
32
29
|
clearTimeout(timer);
|
|
33
30
|
}
|
|
34
31
|
}
|
|
35
32
|
|
|
36
|
-
// GET /v1/memory/stats — also used for key validation.
|
|
37
33
|
function stats(key, opts = {}) {
|
|
38
34
|
return request('GET', '/v1/memory/stats', { key, timeoutMs: opts.timeoutMs || 10000 });
|
|
39
35
|
}
|
|
40
36
|
|
|
41
|
-
// POST /v1/memory/prepare — server-formatted context block for injection.
|
|
42
37
|
function prepare(key, prompt, sessionId, opts = {}) {
|
|
43
|
-
const body = {
|
|
44
|
-
messages: [{ role: 'user', content: prompt }],
|
|
45
|
-
};
|
|
38
|
+
const body = { messages: [{ role: 'user', content: prompt }] };
|
|
46
39
|
if (sessionId) body.session_id = sessionId;
|
|
47
40
|
if (opts.contextLimit) body.context_limit = opts.contextLimit;
|
|
48
41
|
if (opts.density) body.density = opts.density;
|
|
49
42
|
return request('POST', '/v1/memory/prepare', { key, body, timeoutMs: opts.timeoutMs || 6000 });
|
|
50
43
|
}
|
|
51
44
|
|
|
52
|
-
// POST /v1/memory/ingest — 202 fire-and-forget.
|
|
53
45
|
function ingest(key, messages, sessionId, opts = {}) {
|
|
54
46
|
const body = { messages };
|
|
55
47
|
if (sessionId) body.session_id = sessionId;
|
|
48
|
+
if (opts.model) body.model = opts.model;
|
|
56
49
|
return request('POST', '/v1/memory/ingest', { key, body, timeoutMs: opts.timeoutMs || 15000 });
|
|
57
50
|
}
|
|
58
51
|
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
return request('POST', '/v1/memory/warmup', { key, body: {}, timeoutMs: opts.timeoutMs || 10000 });
|
|
52
|
+
function warmup(key, sessionId, opts = {}) {
|
|
53
|
+
const headers = sessionId ? { 'X-Session-ID': sessionId } : {};
|
|
54
|
+
return request('POST', '/v1/memory/warmup', { key, body: {}, headers, timeoutMs: opts.timeoutMs || 10000 });
|
|
62
55
|
}
|
|
63
56
|
|
|
64
57
|
module.exports = { request, stats, prepare, ingest, warmup, debug };
|