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