memoryrouter-claude 1.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/LICENSE +21 -0
- package/README.md +107 -0
- package/bin/cli.js +246 -0
- package/lib/api.js +64 -0
- package/lib/config.js +83 -0
- package/lib/hook-runner.js +215 -0
- package/lib/settings.js +156 -0
- package/lib/transcript.js +63 -0
- package/package.json +43 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 John Rood / MemoryRouter (memoryrouter.ai)
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
# memoryrouter-claude
|
|
2
|
+
|
|
3
|
+
**Persistent memory for Claude Code.** One command installs hooks that give Claude Code a real long-term memory: relevant context injected into every turn, every conversation captured, and nothing lost to compaction — powered by [MemoryRouter](https://memoryrouter.ai).
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
npx memoryrouter-claude init
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
That's it. Paste your Memory Key (free at [app.memoryrouter.ai](https://app.memoryrouter.ai)), pick a scope, and your Claude Code sessions remember everything — across sessions, across machines, across every AI platform connected to your vault.
|
|
10
|
+
|
|
11
|
+
## Why
|
|
12
|
+
|
|
13
|
+
Claude Code's built-in auto memory is local notes per project on one machine. MemoryRouter is a different layer:
|
|
14
|
+
|
|
15
|
+
- **Semantic search** over your full conversation history, not curated notes
|
|
16
|
+
- **Cross-machine** — same memory on your laptop and your server
|
|
17
|
+
- **Cross-platform** — the same vault works in ChatGPT, Claude.ai, OpenClaw, and your own apps
|
|
18
|
+
- **Compaction-proof** — the full transcript is saved *before* Claude Code compacts it away
|
|
19
|
+
|
|
20
|
+
## How it works
|
|
21
|
+
|
|
22
|
+
The installer adds five hooks to your Claude Code settings:
|
|
23
|
+
|
|
24
|
+
```
|
|
25
|
+
┌────────────────────────────────────────────────────────────────┐
|
|
26
|
+
│ Claude Code session │
|
|
27
|
+
│ │
|
|
28
|
+
│ SessionStart ──────► POST /v1/memory/warmup │
|
|
29
|
+
│ (pre-load your vault → fast first recall)│
|
|
30
|
+
│ │
|
|
31
|
+
│ UserPromptSubmit ──► POST /v1/memory/prepare │
|
|
32
|
+
│ (every prompt) relevant memories injected as context │
|
|
33
|
+
│ │
|
|
34
|
+
│ Stop ──────────────► POST /v1/memory/ingest │
|
|
35
|
+
│ (every turn) user prompt + assistant reply captured │
|
|
36
|
+
│ │
|
|
37
|
+
│ PreCompact ────────► POST /v1/memory/ingest │
|
|
38
|
+
│ (before compaction) full un-saved transcript flushed │
|
|
39
|
+
│ │
|
|
40
|
+
│ SessionEnd ────────► POST /v1/memory/ingest │
|
|
41
|
+
│ (session close) final flush │
|
|
42
|
+
└────────────────────────────────────────────────────────────────┘
|
|
43
|
+
api.memoryrouter.ai · Bearer mk_xxx
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
Every hook **fails open**: if the network or API is down, the hook exits 0 instantly and Claude Code continues as if nothing happened. Your prompts are never blocked, ever.
|
|
47
|
+
|
|
48
|
+
## Commands
|
|
49
|
+
|
|
50
|
+
| Command | What it does |
|
|
51
|
+
|---|---|
|
|
52
|
+
| `npx memoryrouter-claude init` | Validate key, install hooks (interactive) |
|
|
53
|
+
| `npx memoryrouter-claude init --key mk_xxx --user --yes` | Non-interactive install for all projects |
|
|
54
|
+
| `npx memoryrouter-claude status` | Key validity + vault stats |
|
|
55
|
+
| `npx memoryrouter-claude off` | Remove our hooks (only ours — your other hooks untouched) |
|
|
56
|
+
| `npx memoryrouter-claude hook <kind>` | Internal — invoked by Claude Code |
|
|
57
|
+
|
|
58
|
+
### Scopes
|
|
59
|
+
|
|
60
|
+
- `--project` (default): writes to `./.claude/settings.json` — this project only, committable
|
|
61
|
+
- `--user`: writes to `~/.claude/settings.json` — every project on this machine
|
|
62
|
+
|
|
63
|
+
The installer **merges** with your existing settings. It never overwrites other hooks or settings, it's idempotent (run it twice, get one set of hooks), and `off` removes exactly what it added.
|
|
64
|
+
|
|
65
|
+
## Configuration
|
|
66
|
+
|
|
67
|
+
| What | Where |
|
|
68
|
+
|---|---|
|
|
69
|
+
| Memory Key | `~/.memoryrouter/config.json` (created with `0600` permissions) |
|
|
70
|
+
| Per-session state | `~/.memoryrouter/state/<session_id>.json` |
|
|
71
|
+
| Env override | `MEMORYROUTER_API_KEY` (takes priority over the config file) |
|
|
72
|
+
| Debug logging | `MEMORYROUTER_DEBUG=1` (hooks log to stderr) |
|
|
73
|
+
| API base override | `MEMORYROUTER_API_BASE` (testing) |
|
|
74
|
+
|
|
75
|
+
Optional knobs in `~/.memoryrouter/config.json`:
|
|
76
|
+
|
|
77
|
+
```json
|
|
78
|
+
{
|
|
79
|
+
"apiKey": "mk_...",
|
|
80
|
+
"contextLimit": 2000,
|
|
81
|
+
"density": "balanced"
|
|
82
|
+
}
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
## Security notes
|
|
86
|
+
|
|
87
|
+
- Your Memory Key is stored **only** in `~/.memoryrouter/config.json` with `0600` permissions — never inside `.claude/settings.json`, so committing project settings never leaks your key.
|
|
88
|
+
- All API traffic is HTTPS to `api.memoryrouter.ai` with `Authorization: Bearer` auth.
|
|
89
|
+
- Want read-only injection with no capture? Use a key with the `:read` suffix (`mk_xxx:read`) — the server skips storage automatically.
|
|
90
|
+
- Nothing is ever sent anywhere except your MemoryRouter vault.
|
|
91
|
+
|
|
92
|
+
## Uninstall
|
|
93
|
+
|
|
94
|
+
```bash
|
|
95
|
+
npx memoryrouter-claude off # removes hooks from project + user settings
|
|
96
|
+
rm -rf ~/.memoryrouter # removes your key + local state
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
## Requirements
|
|
100
|
+
|
|
101
|
+
- Node.js ≥ 18
|
|
102
|
+
- Claude Code
|
|
103
|
+
- A MemoryRouter Memory Key — free at [app.memoryrouter.ai](https://app.memoryrouter.ai)
|
|
104
|
+
|
|
105
|
+
## License
|
|
106
|
+
|
|
107
|
+
MIT © [MemoryRouter](https://memoryrouter.ai)
|
package/bin/cli.js
ADDED
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
// MemoryRouter CLI for Claude Code.
|
|
4
|
+
// Commands: init, status, off|uninstall, hook <kind>
|
|
5
|
+
|
|
6
|
+
const path = require('path');
|
|
7
|
+
const readline = require('readline');
|
|
8
|
+
const {
|
|
9
|
+
loadConfig,
|
|
10
|
+
saveConfig,
|
|
11
|
+
getApiKey,
|
|
12
|
+
CONFIG_PATH,
|
|
13
|
+
} = require('../lib/config');
|
|
14
|
+
const api = require('../lib/api');
|
|
15
|
+
const settingsLib = require('../lib/settings');
|
|
16
|
+
const { runHook } = require('../lib/hook-runner');
|
|
17
|
+
|
|
18
|
+
const VERSION = require('../package.json').version;
|
|
19
|
+
|
|
20
|
+
const HELP = `
|
|
21
|
+
memoryrouter v${VERSION} — persistent memory for Claude Code (memoryrouter.ai)
|
|
22
|
+
|
|
23
|
+
Usage:
|
|
24
|
+
npx memoryrouter-claude init [--key mk_xxx] [--user | --project] [--yes]
|
|
25
|
+
Install memory hooks into Claude Code settings.
|
|
26
|
+
--key Memory Key (or set MEMORYROUTER_API_KEY). Get one at https://app.memoryrouter.ai
|
|
27
|
+
--project Write hooks to ./.claude/settings.json (default)
|
|
28
|
+
--user Write hooks to ~/.claude/settings.json (all projects)
|
|
29
|
+
--yes Skip prompts (use defaults / flags)
|
|
30
|
+
|
|
31
|
+
npx memoryrouter-claude status
|
|
32
|
+
Show key validity + memory stats.
|
|
33
|
+
|
|
34
|
+
npx memoryrouter-claude off [--user | --project]
|
|
35
|
+
Remove MemoryRouter hooks from Claude Code settings (only ours).
|
|
36
|
+
(alias: uninstall)
|
|
37
|
+
|
|
38
|
+
npx memoryrouter-claude hook <inject|capture|flush|session-start>
|
|
39
|
+
Internal — invoked by Claude Code hooks. Always exits 0.
|
|
40
|
+
|
|
41
|
+
Docs: https://memoryrouter.ai/claude-code
|
|
42
|
+
`;
|
|
43
|
+
|
|
44
|
+
function parseArgs(argv) {
|
|
45
|
+
const args = { _: [] };
|
|
46
|
+
for (let i = 0; i < argv.length; i++) {
|
|
47
|
+
const a = argv[i];
|
|
48
|
+
if (a === '--key') args.key = argv[++i];
|
|
49
|
+
else if (a === '--user') args.scope = 'user';
|
|
50
|
+
else if (a === '--project') args.scope = 'project';
|
|
51
|
+
else if (a === '--yes' || a === '-y') args.yes = true;
|
|
52
|
+
else if (a === '--final') args.final = true;
|
|
53
|
+
else if (a === '--help' || a === '-h') args.help = true;
|
|
54
|
+
else if (a === '--version' || a === '-v') args.version = true;
|
|
55
|
+
else args._.push(a);
|
|
56
|
+
}
|
|
57
|
+
return args;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function ask(question) {
|
|
61
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
62
|
+
return new Promise((resolve) =>
|
|
63
|
+
rl.question(question, (answer) => {
|
|
64
|
+
rl.close();
|
|
65
|
+
resolve(answer.trim());
|
|
66
|
+
}),
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
|
|
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
|
+
function resolveBin() {
|
|
75
|
+
const self = path.resolve(__dirname, 'cli.js');
|
|
76
|
+
if (self.includes(`${path.sep}_npx${path.sep}`)) {
|
|
77
|
+
return 'npx -y memoryrouter-claude';
|
|
78
|
+
}
|
|
79
|
+
const nodeBin = process.execPath;
|
|
80
|
+
// Quote paths in case of spaces (e.g. macOS "Application Support")
|
|
81
|
+
return `"${nodeBin}" "${self}"`;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
async function cmdInit(args) {
|
|
85
|
+
console.log(`\n MemoryRouter × Claude Code installer\n`);
|
|
86
|
+
|
|
87
|
+
// 1) Get the key
|
|
88
|
+
let key = args.key || process.env.MEMORYROUTER_API_KEY || loadConfig().apiKey || null;
|
|
89
|
+
if (!key && !args.yes) {
|
|
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
|
+
}
|
|
97
|
+
|
|
98
|
+
// 2) Validate against the API
|
|
99
|
+
process.stdout.write(' Validating key… ');
|
|
100
|
+
let statsRes;
|
|
101
|
+
try {
|
|
102
|
+
statsRes = await api.stats(key);
|
|
103
|
+
} catch (e) {
|
|
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)`);
|
|
115
|
+
|
|
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
|
+
let scope = args.scope;
|
|
124
|
+
if (!scope && !args.yes) {
|
|
125
|
+
const ans = await ask(' Install hooks for [1] this project (.claude/settings.json) or [2] all projects (~/.claude/settings.json)? [1]: ');
|
|
126
|
+
scope = ans === '2' ? 'user' : 'project';
|
|
127
|
+
}
|
|
128
|
+
if (!scope) scope = 'project';
|
|
129
|
+
|
|
130
|
+
const file = settingsLib.settingsPathFor(scope, process.cwd());
|
|
131
|
+
|
|
132
|
+
// 5) Merge hooks (non-destructive)
|
|
133
|
+
const bin = resolveBin();
|
|
134
|
+
try {
|
|
135
|
+
settingsLib.installHooks(file, bin);
|
|
136
|
+
} catch (e) {
|
|
137
|
+
console.error(`\n ✗ ${e.message}\n`);
|
|
138
|
+
process.exit(1);
|
|
139
|
+
}
|
|
140
|
+
console.log(` Hooks installed → ${file}`);
|
|
141
|
+
console.log(`
|
|
142
|
+
Installed hooks:
|
|
143
|
+
SessionStart → warm up your memory vault
|
|
144
|
+
UserPromptSubmit → inject relevant memories into every turn
|
|
145
|
+
Stop → capture each turn to MemoryRouter
|
|
146
|
+
PreCompact → flush full transcript before compaction
|
|
147
|
+
SessionEnd → final flush when the session closes
|
|
148
|
+
|
|
149
|
+
✓ Done. Restart Claude Code (or start a new session) and your
|
|
150
|
+
agent has persistent memory. Run \`npx memoryrouter-claude status\` anytime.
|
|
151
|
+
`);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
async function cmdStatus() {
|
|
155
|
+
const key = getApiKey();
|
|
156
|
+
if (!key) {
|
|
157
|
+
console.error(' ✗ No Memory Key configured. Run: npx memoryrouter-claude init');
|
|
158
|
+
process.exit(1);
|
|
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
|
+
console.log(`
|
|
174
|
+
MemoryRouter status
|
|
175
|
+
───────────────────
|
|
176
|
+
Key: ${masked} ✓ valid
|
|
177
|
+
Memories: ${s.totalVectors ?? s.total_vectors ?? '?'} vectors
|
|
178
|
+
Tokens: ${s.totalTokens ?? s.total_tokens ?? '?'}
|
|
179
|
+
Storage: ${s.storage ?? '?'}
|
|
180
|
+
Oldest: ${s.oldestItem ? new Date(s.oldestItem).toISOString() : '—'}
|
|
181
|
+
Newest: ${s.newestItem ? new Date(s.newestItem).toISOString() : '—'}
|
|
182
|
+
`);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
async function cmdOff(args) {
|
|
186
|
+
const scopes = args.scope ? [args.scope] : ['project', 'user'];
|
|
187
|
+
let removedAny = false;
|
|
188
|
+
for (const scope of scopes) {
|
|
189
|
+
const file = settingsLib.settingsPathFor(scope, process.cwd());
|
|
190
|
+
const result = settingsLib.uninstallHooks(file);
|
|
191
|
+
if (result !== null) {
|
|
192
|
+
console.log(` Removed MemoryRouter hooks from ${file}`);
|
|
193
|
+
removedAny = true;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
if (!removedAny) console.log(' No MemoryRouter hooks found.');
|
|
197
|
+
console.log(` (Your Memory Key remains in ${CONFIG_PATH} — delete that file to remove it.)`);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
async function main() {
|
|
201
|
+
const args = parseArgs(process.argv.slice(2));
|
|
202
|
+
const cmd = args._[0];
|
|
203
|
+
|
|
204
|
+
if (args.version) {
|
|
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
|
+
|
|
218
|
+
switch (cmd) {
|
|
219
|
+
case 'init':
|
|
220
|
+
await cmdInit(args);
|
|
221
|
+
break;
|
|
222
|
+
case 'status':
|
|
223
|
+
await cmdStatus();
|
|
224
|
+
break;
|
|
225
|
+
case 'off':
|
|
226
|
+
case 'uninstall':
|
|
227
|
+
await cmdOff(args);
|
|
228
|
+
break;
|
|
229
|
+
case 'hook':
|
|
230
|
+
await runHook(args._[1]);
|
|
231
|
+
break;
|
|
232
|
+
default:
|
|
233
|
+
console.log(HELP);
|
|
234
|
+
process.exit(cmd ? 1 : 0);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
main().catch((err) => {
|
|
239
|
+
// hook subcommand must never fail; others may report
|
|
240
|
+
if (process.argv[2] === 'hook') {
|
|
241
|
+
if (process.env.MEMORYROUTER_DEBUG) console.error('[memoryrouter]', err);
|
|
242
|
+
process.exit(0);
|
|
243
|
+
}
|
|
244
|
+
console.error(' ✗ ' + (err && err.message));
|
|
245
|
+
process.exit(1);
|
|
246
|
+
});
|
package/lib/api.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Minimal MemoryRouter API client. Node 18+ built-in fetch. No deps.
|
|
3
|
+
|
|
4
|
+
const { API_BASE } = require('./config');
|
|
5
|
+
|
|
6
|
+
function debug(...args) {
|
|
7
|
+
if (process.env.MEMORYROUTER_DEBUG) console.error('[memoryrouter]', ...args);
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
async function request(method, endpoint, { key, body, timeoutMs = 8000 } = {}) {
|
|
11
|
+
const ctrl = new AbortController();
|
|
12
|
+
const timer = setTimeout(() => ctrl.abort(), timeoutMs);
|
|
13
|
+
try {
|
|
14
|
+
const res = await fetch(API_BASE + endpoint, {
|
|
15
|
+
method,
|
|
16
|
+
headers: {
|
|
17
|
+
Authorization: `Bearer ${key}`,
|
|
18
|
+
'Content-Type': 'application/json',
|
|
19
|
+
'User-Agent': 'memoryrouter-claude-code/1.0.0',
|
|
20
|
+
},
|
|
21
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
22
|
+
signal: ctrl.signal,
|
|
23
|
+
});
|
|
24
|
+
let data = null;
|
|
25
|
+
try {
|
|
26
|
+
data = await res.json();
|
|
27
|
+
} catch {
|
|
28
|
+
/* non-JSON body */
|
|
29
|
+
}
|
|
30
|
+
return { ok: res.ok, status: res.status, data };
|
|
31
|
+
} finally {
|
|
32
|
+
clearTimeout(timer);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// GET /v1/memory/stats — also used for key validation.
|
|
37
|
+
function stats(key, opts = {}) {
|
|
38
|
+
return request('GET', '/v1/memory/stats', { key, timeoutMs: opts.timeoutMs || 10000 });
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// POST /v1/memory/prepare — server-formatted context block for injection.
|
|
42
|
+
function prepare(key, prompt, sessionId, opts = {}) {
|
|
43
|
+
const body = {
|
|
44
|
+
messages: [{ role: 'user', content: prompt }],
|
|
45
|
+
};
|
|
46
|
+
if (sessionId) body.session_id = sessionId;
|
|
47
|
+
if (opts.contextLimit) body.context_limit = opts.contextLimit;
|
|
48
|
+
if (opts.density) body.density = opts.density;
|
|
49
|
+
return request('POST', '/v1/memory/prepare', { key, body, timeoutMs: opts.timeoutMs || 6000 });
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// POST /v1/memory/ingest — 202 fire-and-forget.
|
|
53
|
+
function ingest(key, messages, sessionId, opts = {}) {
|
|
54
|
+
const body = { messages };
|
|
55
|
+
if (sessionId) body.session_id = sessionId;
|
|
56
|
+
return request('POST', '/v1/memory/ingest', { key, body, timeoutMs: opts.timeoutMs || 15000 });
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// POST /v1/memory/warmup — preload vault vectors for fast first search.
|
|
60
|
+
function warmup(key, opts = {}) {
|
|
61
|
+
return request('POST', '/v1/memory/warmup', { key, body: {}, timeoutMs: opts.timeoutMs || 10000 });
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
module.exports = { request, stats, prepare, ingest, warmup, debug };
|
package/lib/config.js
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Config + state storage for the MemoryRouter Claude Code integration.
|
|
3
|
+
// Key lives in ~/.memoryrouter/config.json (0600), NOT in Claude settings JSON.
|
|
4
|
+
|
|
5
|
+
const fs = require('fs');
|
|
6
|
+
const path = require('path');
|
|
7
|
+
const os = require('os');
|
|
8
|
+
|
|
9
|
+
const CONFIG_DIR = process.env.MEMORYROUTER_CONFIG_DIR || path.join(os.homedir(), '.memoryrouter');
|
|
10
|
+
const CONFIG_PATH = path.join(CONFIG_DIR, 'config.json');
|
|
11
|
+
const STATE_DIR = path.join(CONFIG_DIR, 'state');
|
|
12
|
+
|
|
13
|
+
const API_BASE = process.env.MEMORYROUTER_API_BASE || 'https://api.memoryrouter.ai';
|
|
14
|
+
|
|
15
|
+
function ensureDir(dir) {
|
|
16
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function readJsonSafe(file) {
|
|
20
|
+
try {
|
|
21
|
+
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
22
|
+
} catch {
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function writeJsonPrivate(file, obj) {
|
|
28
|
+
ensureDir(path.dirname(file));
|
|
29
|
+
const tmp = file + '.tmp';
|
|
30
|
+
fs.writeFileSync(tmp, JSON.stringify(obj, null, 2) + '\n', { mode: 0o600 });
|
|
31
|
+
fs.renameSync(tmp, file);
|
|
32
|
+
try {
|
|
33
|
+
fs.chmodSync(file, 0o600);
|
|
34
|
+
} catch {
|
|
35
|
+
/* windows best-effort */
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function loadConfig() {
|
|
40
|
+
return readJsonSafe(CONFIG_PATH) || {};
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function saveConfig(cfg) {
|
|
44
|
+
writeJsonPrivate(CONFIG_PATH, cfg);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// Resolution order: env var > config file.
|
|
48
|
+
function getApiKey() {
|
|
49
|
+
if (process.env.MEMORYROUTER_API_KEY) return process.env.MEMORYROUTER_API_KEY.trim();
|
|
50
|
+
const cfg = loadConfig();
|
|
51
|
+
return cfg.apiKey || null;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// --- per-session state (high-water mark for transcript ingestion, cached prompt) ---
|
|
55
|
+
|
|
56
|
+
function statePath(sessionId) {
|
|
57
|
+
// session ids are uuid-ish; sanitize defensively
|
|
58
|
+
const safe = String(sessionId || 'unknown').replace(/[^a-zA-Z0-9_-]/g, '_').slice(0, 128);
|
|
59
|
+
return path.join(STATE_DIR, safe + '.json');
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function loadState(sessionId) {
|
|
63
|
+
return readJsonSafe(statePath(sessionId)) || {};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function saveState(sessionId, state) {
|
|
67
|
+
writeJsonPrivate(statePath(sessionId), state);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
module.exports = {
|
|
71
|
+
CONFIG_DIR,
|
|
72
|
+
CONFIG_PATH,
|
|
73
|
+
STATE_DIR,
|
|
74
|
+
API_BASE,
|
|
75
|
+
loadConfig,
|
|
76
|
+
saveConfig,
|
|
77
|
+
getApiKey,
|
|
78
|
+
loadState,
|
|
79
|
+
saveState,
|
|
80
|
+
statePath,
|
|
81
|
+
writeJsonPrivate,
|
|
82
|
+
readJsonSafe,
|
|
83
|
+
};
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Hook runtime invoked by Claude Code: `memoryrouter hook <inject|capture|flush|session-start>`
|
|
3
|
+
// Contract: ALWAYS exit 0 (fail open). Never block the user. Errors go to stderr
|
|
4
|
+
// only when MEMORYROUTER_DEBUG=1.
|
|
5
|
+
|
|
6
|
+
const { getApiKey, loadState, saveState, loadConfig } = require('./config');
|
|
7
|
+
const api = require('./api');
|
|
8
|
+
const { readTranscript } = require('./transcript');
|
|
9
|
+
|
|
10
|
+
const MAX_CONTEXT_CHARS = 9500; // stay under Claude Code's 10k additionalContext cap
|
|
11
|
+
|
|
12
|
+
function debug(...args) {
|
|
13
|
+
if (process.env.MEMORYROUTER_DEBUG) console.error('[memoryrouter]', ...args);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function readStdin(timeoutMs = 2000) {
|
|
17
|
+
return new Promise((resolve) => {
|
|
18
|
+
let data = '';
|
|
19
|
+
const timer = setTimeout(() => resolve(data), timeoutMs);
|
|
20
|
+
process.stdin.setEncoding('utf8');
|
|
21
|
+
process.stdin.on('data', (chunk) => (data += chunk));
|
|
22
|
+
process.stdin.on('end', () => {
|
|
23
|
+
clearTimeout(timer);
|
|
24
|
+
resolve(data);
|
|
25
|
+
});
|
|
26
|
+
process.stdin.on('error', () => {
|
|
27
|
+
clearTimeout(timer);
|
|
28
|
+
resolve(data);
|
|
29
|
+
});
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function emitContext(eventName, context) {
|
|
34
|
+
if (!context || typeof context !== 'string' || !context.trim()) return;
|
|
35
|
+
let text = context;
|
|
36
|
+
if (text.length > MAX_CONTEXT_CHARS) {
|
|
37
|
+
text = text.slice(0, MAX_CONTEXT_CHARS) + '\n[memory context truncated]';
|
|
38
|
+
}
|
|
39
|
+
process.stdout.write(
|
|
40
|
+
JSON.stringify({
|
|
41
|
+
hookSpecificOutput: {
|
|
42
|
+
hookEventName: eventName,
|
|
43
|
+
additionalContext: text,
|
|
44
|
+
},
|
|
45
|
+
}),
|
|
46
|
+
);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// --- handlers ---
|
|
50
|
+
|
|
51
|
+
async function handleInject(input, key) {
|
|
52
|
+
const prompt = input.prompt;
|
|
53
|
+
if (!prompt || typeof prompt !== 'string' || !prompt.trim()) return;
|
|
54
|
+
const sessionId = input.session_id;
|
|
55
|
+
|
|
56
|
+
// Cache the prompt so the Stop hook can pair it with the assistant reply.
|
|
57
|
+
try {
|
|
58
|
+
const state = loadState(sessionId);
|
|
59
|
+
state.lastPrompt = prompt.slice(0, 100000);
|
|
60
|
+
state.lastPromptAt = Date.now();
|
|
61
|
+
saveState(sessionId, state);
|
|
62
|
+
} catch (e) {
|
|
63
|
+
debug('state cache failed:', e.message);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const cfg = loadConfig();
|
|
67
|
+
const res = await api.prepare(key, prompt, sessionId, {
|
|
68
|
+
timeoutMs: 6000,
|
|
69
|
+
contextLimit: cfg.contextLimit,
|
|
70
|
+
density: cfg.density,
|
|
71
|
+
});
|
|
72
|
+
if (!res.ok || !res.data) {
|
|
73
|
+
debug('prepare failed:', res.status);
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
emitContext('UserPromptSubmit', res.data.context);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async function handleCapture(input, key) {
|
|
80
|
+
// Loop guard: when Claude continues due to a stop hook, don't re-ingest.
|
|
81
|
+
if (input.stop_hook_active) {
|
|
82
|
+
debug('stop_hook_active — skipping capture');
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
const sessionId = input.session_id;
|
|
86
|
+
const assistant = input.last_assistant_message;
|
|
87
|
+
if (!assistant || typeof assistant !== 'string' || !assistant.trim()) {
|
|
88
|
+
debug('no last_assistant_message — skipping');
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const messages = [];
|
|
93
|
+
let state = {};
|
|
94
|
+
try {
|
|
95
|
+
state = loadState(sessionId);
|
|
96
|
+
} catch {
|
|
97
|
+
/* ignore */
|
|
98
|
+
}
|
|
99
|
+
if (state.lastPrompt) {
|
|
100
|
+
messages.push({ role: 'user', content: state.lastPrompt });
|
|
101
|
+
}
|
|
102
|
+
messages.push({ role: 'assistant', content: assistant });
|
|
103
|
+
|
|
104
|
+
const res = await api.ingest(key, messages, sessionId, { timeoutMs: 10000 });
|
|
105
|
+
debug('ingest status:', res.status);
|
|
106
|
+
|
|
107
|
+
// Advance the transcript high-water mark so PreCompact/SessionEnd flushes
|
|
108
|
+
// don't re-send what per-turn capture already stored.
|
|
109
|
+
try {
|
|
110
|
+
if (input.transcript_path) {
|
|
111
|
+
const { lastLine } = readTranscript(input.transcript_path, -1);
|
|
112
|
+
state.highWaterLine = lastLine;
|
|
113
|
+
}
|
|
114
|
+
delete state.lastPrompt;
|
|
115
|
+
state.lastCaptureAt = Date.now();
|
|
116
|
+
saveState(sessionId, state);
|
|
117
|
+
} catch (e) {
|
|
118
|
+
debug('state update failed:', e.message);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
async function handleFlush(input, key) {
|
|
123
|
+
const sessionId = input.session_id;
|
|
124
|
+
if (!input.transcript_path) return;
|
|
125
|
+
let state = {};
|
|
126
|
+
try {
|
|
127
|
+
state = loadState(sessionId);
|
|
128
|
+
} catch {
|
|
129
|
+
/* ignore */
|
|
130
|
+
}
|
|
131
|
+
const after = Number.isInteger(state.highWaterLine) ? state.highWaterLine : -1;
|
|
132
|
+
const { messages, lastLine } = readTranscript(input.transcript_path, after);
|
|
133
|
+
if (messages.length === 0) {
|
|
134
|
+
debug('flush: nothing new to ingest');
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
// Cap batch size defensively (server chunks in background anyway)
|
|
138
|
+
const batch = messages.slice(-200);
|
|
139
|
+
const res = await api.ingest(key, batch, sessionId, { timeoutMs: 20000 });
|
|
140
|
+
debug('flush ingest status:', res.status, 'messages:', batch.length);
|
|
141
|
+
try {
|
|
142
|
+
state.highWaterLine = lastLine;
|
|
143
|
+
state.lastFlushAt = Date.now();
|
|
144
|
+
saveState(sessionId, state);
|
|
145
|
+
} catch (e) {
|
|
146
|
+
debug('state update failed:', e.message);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
async function handleSessionStart(input, key) {
|
|
151
|
+
// Fire-and-forget warmup so the first search/prepare is fast.
|
|
152
|
+
try {
|
|
153
|
+
await api.warmup(key, { timeoutMs: 8000 });
|
|
154
|
+
} catch (e) {
|
|
155
|
+
debug('warmup failed:', e.message);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// --- entry ---
|
|
160
|
+
|
|
161
|
+
async function runHook(kind) {
|
|
162
|
+
// Absolute wall-clock kill switch: never hang past our settings timeout.
|
|
163
|
+
const wallClock = setTimeout(() => {
|
|
164
|
+
debug('wall-clock timeout — exiting 0');
|
|
165
|
+
process.exit(0);
|
|
166
|
+
}, kind === 'inject' ? 8000 : 25000);
|
|
167
|
+
wallClock.unref();
|
|
168
|
+
|
|
169
|
+
try {
|
|
170
|
+
const key = getApiKey();
|
|
171
|
+
if (!key) {
|
|
172
|
+
debug('no API key configured — run `npx memoryrouter-claude init`');
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
const raw = await readStdin();
|
|
176
|
+
let input = {};
|
|
177
|
+
try {
|
|
178
|
+
input = JSON.parse(raw || '{}');
|
|
179
|
+
} catch {
|
|
180
|
+
debug('bad stdin JSON');
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
switch (kind) {
|
|
185
|
+
case 'inject':
|
|
186
|
+
await handleInject(input, key);
|
|
187
|
+
break;
|
|
188
|
+
case 'capture':
|
|
189
|
+
await handleCapture(input, key);
|
|
190
|
+
break;
|
|
191
|
+
case 'flush':
|
|
192
|
+
await handleFlush(input, key);
|
|
193
|
+
break;
|
|
194
|
+
case 'session-start':
|
|
195
|
+
await handleSessionStart(input, key);
|
|
196
|
+
break;
|
|
197
|
+
default:
|
|
198
|
+
debug('unknown hook kind:', kind);
|
|
199
|
+
}
|
|
200
|
+
} catch (err) {
|
|
201
|
+
debug('hook error:', err && err.message);
|
|
202
|
+
}
|
|
203
|
+
// Always success — fail open.
|
|
204
|
+
process.exitCode = 0;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
module.exports = {
|
|
208
|
+
runHook,
|
|
209
|
+
handleInject,
|
|
210
|
+
handleCapture,
|
|
211
|
+
handleFlush,
|
|
212
|
+
handleSessionStart,
|
|
213
|
+
emitContext,
|
|
214
|
+
MAX_CONTEXT_CHARS,
|
|
215
|
+
};
|
package/lib/settings.js
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Non-destructive merge/removal of MemoryRouter hooks into Claude Code settings JSON.
|
|
3
|
+
// We tag every hook command we own with the marker string so uninstall removes
|
|
4
|
+
// ONLY our hooks and never touches anything else in the file.
|
|
5
|
+
|
|
6
|
+
const fs = require('fs');
|
|
7
|
+
const path = require('path');
|
|
8
|
+
const os = require('os');
|
|
9
|
+
|
|
10
|
+
// Ours = command mentions memoryrouter (package/path, case-insensitive) AND
|
|
11
|
+
// invokes one of our hook kinds. This survives both `npx -y memoryrouter-claude hook X`
|
|
12
|
+
// and absolute-path installs like `"node" ".../memoryrouter/bin/cli.js" hook X`.
|
|
13
|
+
const OURS_RE = /memoryrouter/i;
|
|
14
|
+
const HOOK_RE = /\bhook (inject|capture|flush|session-start)\b/;
|
|
15
|
+
|
|
16
|
+
// Hook definitions per the research spec (section b).
|
|
17
|
+
// `bin` is the command prefix to invoke us — absolute path when possible, npx fallback.
|
|
18
|
+
function buildHookConfig(bin) {
|
|
19
|
+
return {
|
|
20
|
+
SessionStart: [
|
|
21
|
+
{
|
|
22
|
+
matcher: 'startup|resume',
|
|
23
|
+
hooks: [{ type: 'command', command: `${bin} hook session-start`, timeout: 15 }],
|
|
24
|
+
},
|
|
25
|
+
],
|
|
26
|
+
UserPromptSubmit: [
|
|
27
|
+
{
|
|
28
|
+
hooks: [{ type: 'command', command: `${bin} hook inject`, timeout: 10 }],
|
|
29
|
+
},
|
|
30
|
+
],
|
|
31
|
+
Stop: [
|
|
32
|
+
{
|
|
33
|
+
hooks: [{ type: 'command', command: `${bin} hook capture`, timeout: 30 }],
|
|
34
|
+
},
|
|
35
|
+
],
|
|
36
|
+
PreCompact: [
|
|
37
|
+
{
|
|
38
|
+
matcher: 'auto|manual',
|
|
39
|
+
hooks: [{ type: 'command', command: `${bin} hook flush`, timeout: 30 }],
|
|
40
|
+
},
|
|
41
|
+
],
|
|
42
|
+
SessionEnd: [
|
|
43
|
+
{
|
|
44
|
+
hooks: [{ type: 'command', command: `${bin} hook flush --final`, timeout: 30 }],
|
|
45
|
+
},
|
|
46
|
+
],
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function isOurs(hookEntry) {
|
|
51
|
+
return (
|
|
52
|
+
hookEntry &&
|
|
53
|
+
hookEntry.type === 'command' &&
|
|
54
|
+
typeof hookEntry.command === 'string' &&
|
|
55
|
+
OURS_RE.test(hookEntry.command) &&
|
|
56
|
+
HOOK_RE.test(hookEntry.command)
|
|
57
|
+
);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// Remove our hooks from a settings object (mutates a deep copy, returns it).
|
|
61
|
+
function removeOurHooks(settings) {
|
|
62
|
+
const out = JSON.parse(JSON.stringify(settings || {}));
|
|
63
|
+
if (!out.hooks || typeof out.hooks !== 'object') return out;
|
|
64
|
+
for (const event of Object.keys(out.hooks)) {
|
|
65
|
+
const matchers = out.hooks[event];
|
|
66
|
+
if (!Array.isArray(matchers)) continue;
|
|
67
|
+
const kept = [];
|
|
68
|
+
for (const m of matchers) {
|
|
69
|
+
if (!m || !Array.isArray(m.hooks)) {
|
|
70
|
+
kept.push(m);
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
const remaining = m.hooks.filter((h) => !isOurs(h));
|
|
74
|
+
if (remaining.length > 0) {
|
|
75
|
+
kept.push({ ...m, hooks: remaining });
|
|
76
|
+
}
|
|
77
|
+
// if all hooks in this matcher group were ours, drop the group
|
|
78
|
+
}
|
|
79
|
+
if (kept.length > 0) out.hooks[event] = kept;
|
|
80
|
+
else delete out.hooks[event];
|
|
81
|
+
}
|
|
82
|
+
if (Object.keys(out.hooks).length === 0) delete out.hooks;
|
|
83
|
+
return out;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// Merge our hooks into a settings object non-destructively.
|
|
87
|
+
// Strategy: first strip any previous MemoryRouter hooks (idempotent re-init),
|
|
88
|
+
// then append our matcher groups to each event's array.
|
|
89
|
+
function mergeHooks(settings, bin) {
|
|
90
|
+
const out = removeOurHooks(settings);
|
|
91
|
+
const ours = buildHookConfig(bin);
|
|
92
|
+
if (!out.hooks || typeof out.hooks !== 'object') out.hooks = {};
|
|
93
|
+
for (const [event, groups] of Object.entries(ours)) {
|
|
94
|
+
if (!Array.isArray(out.hooks[event])) out.hooks[event] = [];
|
|
95
|
+
out.hooks[event] = out.hooks[event].concat(groups);
|
|
96
|
+
}
|
|
97
|
+
return out;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// --- file-level helpers ---
|
|
101
|
+
|
|
102
|
+
function settingsPathFor(scope, cwd) {
|
|
103
|
+
if (scope === 'user') return path.join(os.homedir(), '.claude', 'settings.json');
|
|
104
|
+
return path.join(cwd || process.cwd(), '.claude', 'settings.json');
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function readSettings(file) {
|
|
108
|
+
try {
|
|
109
|
+
const text = fs.readFileSync(file, 'utf8');
|
|
110
|
+
return JSON.parse(text);
|
|
111
|
+
} catch (err) {
|
|
112
|
+
if (err.code === 'ENOENT') return {};
|
|
113
|
+
throw new Error(`Could not parse ${file}: ${err.message}. Fix or move the file and retry.`);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function writeSettings(file, settings) {
|
|
118
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
119
|
+
const tmp = file + '.tmp';
|
|
120
|
+
fs.writeFileSync(tmp, JSON.stringify(settings, null, 2) + '\n');
|
|
121
|
+
fs.renameSync(tmp, file);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function installHooks(file, bin) {
|
|
125
|
+
const settings = readSettings(file);
|
|
126
|
+
const merged = mergeHooks(settings, bin);
|
|
127
|
+
writeSettings(file, merged);
|
|
128
|
+
return merged;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function uninstallHooks(file) {
|
|
132
|
+
let settings;
|
|
133
|
+
try {
|
|
134
|
+
settings = readSettings(file);
|
|
135
|
+
} catch {
|
|
136
|
+
return null; // unparseable — don't touch
|
|
137
|
+
}
|
|
138
|
+
if (!settings || Object.keys(settings).length === 0) return null;
|
|
139
|
+
const cleaned = removeOurHooks(settings);
|
|
140
|
+
writeSettings(file, cleaned);
|
|
141
|
+
return cleaned;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
module.exports = {
|
|
145
|
+
OURS_RE,
|
|
146
|
+
HOOK_RE,
|
|
147
|
+
buildHookConfig,
|
|
148
|
+
isOurs,
|
|
149
|
+
mergeHooks,
|
|
150
|
+
removeOurHooks,
|
|
151
|
+
settingsPathFor,
|
|
152
|
+
readSettings,
|
|
153
|
+
writeSettings,
|
|
154
|
+
installHooks,
|
|
155
|
+
uninstallHooks,
|
|
156
|
+
};
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Claude Code transcript (JSONL) parsing.
|
|
3
|
+
// Each line is a JSON object; conversation messages have shape roughly:
|
|
4
|
+
// { "type": "user"|"assistant", "uuid": "...", "message": { "role": "...", "content": "..."|[{type:"text",text:"..."}, ...] }, ... }
|
|
5
|
+
// We extract plain-text user/assistant messages above a high-water mark (line index).
|
|
6
|
+
|
|
7
|
+
const fs = require('fs');
|
|
8
|
+
|
|
9
|
+
// Pull plain text out of a message content field (string or content-block array).
|
|
10
|
+
function contentToText(content) {
|
|
11
|
+
if (typeof content === 'string') return content;
|
|
12
|
+
if (Array.isArray(content)) {
|
|
13
|
+
return content
|
|
14
|
+
.filter((b) => b && b.type === 'text' && typeof b.text === 'string')
|
|
15
|
+
.map((b) => b.text)
|
|
16
|
+
.join('\n');
|
|
17
|
+
}
|
|
18
|
+
return '';
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// Parse transcript lines into [{role, content}], starting AFTER line index `afterLine`
|
|
22
|
+
// (-1 = from the beginning). Returns { messages, lastLine } where lastLine is the
|
|
23
|
+
// index of the last line in the file (new high-water mark).
|
|
24
|
+
function parseTranscript(jsonlText, afterLine = -1) {
|
|
25
|
+
const lines = jsonlText.split('\n');
|
|
26
|
+
const messages = [];
|
|
27
|
+
let lastLine = afterLine;
|
|
28
|
+
for (let i = 0; i < lines.length; i++) {
|
|
29
|
+
const line = lines[i].trim();
|
|
30
|
+
if (!line) continue;
|
|
31
|
+
lastLine = i;
|
|
32
|
+
if (i <= afterLine) continue;
|
|
33
|
+
let obj;
|
|
34
|
+
try {
|
|
35
|
+
obj = JSON.parse(line);
|
|
36
|
+
} catch {
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
// Skip meta/sidechain entries
|
|
40
|
+
if (obj.isSidechain) continue;
|
|
41
|
+
const msg = obj.message;
|
|
42
|
+
if (!msg || !msg.role) continue;
|
|
43
|
+
if (msg.role !== 'user' && msg.role !== 'assistant') continue;
|
|
44
|
+
const text = contentToText(msg.content);
|
|
45
|
+
if (!text || !text.trim()) continue;
|
|
46
|
+
// Skip tool-result-only user entries and system-reminder noise
|
|
47
|
+
if (text.startsWith('<system-reminder>')) continue;
|
|
48
|
+
messages.push({ role: msg.role, content: text });
|
|
49
|
+
}
|
|
50
|
+
return { messages, lastLine };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function readTranscript(transcriptPath, afterLine = -1) {
|
|
54
|
+
let text;
|
|
55
|
+
try {
|
|
56
|
+
text = fs.readFileSync(transcriptPath, 'utf8');
|
|
57
|
+
} catch {
|
|
58
|
+
return { messages: [], lastLine: afterLine };
|
|
59
|
+
}
|
|
60
|
+
return parseTranscript(text, afterLine);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
module.exports = { parseTranscript, readTranscript, contentToText };
|
package/package.json
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "memoryrouter-claude",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Persistent memory for Claude Code. One command installs hooks that inject relevant memories every turn, capture every conversation, and flush context before compaction — powered by MemoryRouter.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "John Rood <john@memoryrouter.ai>",
|
|
7
|
+
"homepage": "https://memoryrouter.ai",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/John-Rood/MemoryRouter.git",
|
|
11
|
+
"directory": "integrations/claude-code"
|
|
12
|
+
},
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/John-Rood/MemoryRouter/issues"
|
|
15
|
+
},
|
|
16
|
+
"keywords": [
|
|
17
|
+
"claude",
|
|
18
|
+
"claude-code",
|
|
19
|
+
"memory",
|
|
20
|
+
"ai",
|
|
21
|
+
"hooks",
|
|
22
|
+
"persistent-memory",
|
|
23
|
+
"memoryrouter",
|
|
24
|
+
"context",
|
|
25
|
+
"agent"
|
|
26
|
+
],
|
|
27
|
+
"bin": {
|
|
28
|
+
"memoryrouter-claude": "bin/cli.js"
|
|
29
|
+
},
|
|
30
|
+
"main": "lib/hook-runner.js",
|
|
31
|
+
"files": [
|
|
32
|
+
"bin/",
|
|
33
|
+
"lib/",
|
|
34
|
+
"README.md",
|
|
35
|
+
"LICENSE"
|
|
36
|
+
],
|
|
37
|
+
"engines": {
|
|
38
|
+
"node": ">=18.0.0"
|
|
39
|
+
},
|
|
40
|
+
"scripts": {
|
|
41
|
+
"test": "node --test 'test/*.test.js'"
|
|
42
|
+
}
|
|
43
|
+
}
|