create-ai-memory 0.12.0 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +403 -3
- package/bin/ai-mem-mcp.js +274 -0
- package/bin/ai-mem-serve.js +240 -0
- package/package.json +11 -7
- package/shell/adapters.zsh +25 -12
- package/shell/ai-mem.zsh +238 -93
- package/vault-template/_session_logs/_session_template.md +1 -0
- package/web/viewer.html +666 -0
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* ai-mem-mcp: expose the vault to agents that have no shell.
|
|
4
|
+
*
|
|
5
|
+
* The `*-start` launchers reach an agent by injecting the vault context into
|
|
6
|
+
* its opening prompt. A GUI opened from the Dock never runs one, so Claude
|
|
7
|
+
* Desktop and the Cursor GUI see nothing -- there is no daemon, and the link
|
|
8
|
+
* is the prompt rather than a service.
|
|
9
|
+
*
|
|
10
|
+
* MCP is the only channel those clients have. This deliberately does NOT
|
|
11
|
+
* apply to anything with Bash: an agent with a shell should call
|
|
12
|
+
* `ai-mem-search` directly rather than through a wrapper that can only get
|
|
13
|
+
* out of date.
|
|
14
|
+
*
|
|
15
|
+
* Every tool shells out to the same zsh functions the CLI uses, so the search
|
|
16
|
+
* and context rules have exactly one implementation. Re-implementing them
|
|
17
|
+
* here in JavaScript would create a second copy to drift.
|
|
18
|
+
*
|
|
19
|
+
* Speaks JSON-RPC 2.0 over stdio, newline-delimited, with no dependencies --
|
|
20
|
+
* the package ships zero and CI refuses to publish if one appears.
|
|
21
|
+
*
|
|
22
|
+
* Register it with a client, e.g. Claude Desktop's config:
|
|
23
|
+
* { "mcpServers": { "ai-memory": { "command": "ai-mem-mcp" } } }
|
|
24
|
+
*/
|
|
25
|
+
'use strict';
|
|
26
|
+
|
|
27
|
+
const { spawnSync, spawn } = require('node:child_process');
|
|
28
|
+
const { realpathSync, existsSync, readFileSync } = require('node:fs');
|
|
29
|
+
const { join, resolve } = require('node:path');
|
|
30
|
+
const { homedir } = require('node:os');
|
|
31
|
+
const readline = require('node:readline');
|
|
32
|
+
|
|
33
|
+
const MODULE = join(__dirname, '..', 'shell', 'ai-mem.zsh');
|
|
34
|
+
const VAULT = process.env.AI_MEM_ROOT || join(homedir(), '.ai-memory', '_Ai_Memory');
|
|
35
|
+
const VERSION = (() => {
|
|
36
|
+
try {
|
|
37
|
+
return JSON.parse(readFileSync(join(__dirname, '..', 'package.json'), 'utf8')).version;
|
|
38
|
+
} catch {
|
|
39
|
+
return '0.0.0';
|
|
40
|
+
}
|
|
41
|
+
})();
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Run a zsh snippet with the module sourced, and return its output.
|
|
45
|
+
*
|
|
46
|
+
* stderr is kept separate and only surfaced when the call fails: sourcing the
|
|
47
|
+
* module prints nothing on success, but a broken vault path should reach the
|
|
48
|
+
* client as an error rather than be silently mixed into a result.
|
|
49
|
+
*
|
|
50
|
+
* @param {string} snippet zsh to run after the module is sourced
|
|
51
|
+
* @returns {{ok: boolean, text: string}}
|
|
52
|
+
*/
|
|
53
|
+
function zsh(snippet) {
|
|
54
|
+
const r = spawnSync('zsh', ['-c', `source ${JSON.stringify(MODULE)} >/dev/null 2>&1\n${snippet}`], {
|
|
55
|
+
encoding: 'utf8',
|
|
56
|
+
env: { ...process.env, AI_MEM_ROOT: VAULT },
|
|
57
|
+
maxBuffer: 8 * 1024 * 1024,
|
|
58
|
+
});
|
|
59
|
+
if (r.error) return { ok: false, text: `failed to run zsh: ${r.error.message}` };
|
|
60
|
+
const out = (r.stdout || '').trim();
|
|
61
|
+
// ai-mem-search exits non-zero for "no matches", which is a real answer and
|
|
62
|
+
// not an error -- the client needs to see it, so only treat an empty result
|
|
63
|
+
// as a failure.
|
|
64
|
+
if (out) return { ok: true, text: out };
|
|
65
|
+
return { ok: false, text: (r.stderr || '').trim() || 'no output' };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Shell-quote a value for safe interpolation into the zsh snippet. */
|
|
69
|
+
const q = (s) => `'${String(s).replace(/'/g, `'\\''`)}'`;
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Resolve a note path and refuse anything outside the vault.
|
|
73
|
+
*
|
|
74
|
+
* Compares resolved real paths with a separator-terminated prefix, not a
|
|
75
|
+
* string prefix: a plain `startsWith` would accept both `<vault>/../etc` and a
|
|
76
|
+
* sibling directory whose name merely begins with the vault's.
|
|
77
|
+
*
|
|
78
|
+
* @param {string} p caller-supplied path, absolute or vault-relative
|
|
79
|
+
* @returns {string|null} the real path, or null if it escapes the vault
|
|
80
|
+
*/
|
|
81
|
+
function insideVault(p) {
|
|
82
|
+
try {
|
|
83
|
+
const root = realpathSync(VAULT);
|
|
84
|
+
const target = realpathSync(resolve(p.startsWith('/') ? p : join(VAULT, p)));
|
|
85
|
+
return target === root || target.startsWith(root + '/') ? target : null;
|
|
86
|
+
} catch {
|
|
87
|
+
return null;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Ambient guidance, returned from `initialize` and surfaced by the client
|
|
93
|
+
* before the first turn.
|
|
94
|
+
*
|
|
95
|
+
* This is what makes a GUI behave like a launcher. In a terminal the vault is
|
|
96
|
+
* pushed into the agent's opening prompt; over MCP nothing is pushed, and a
|
|
97
|
+
* model with no reason to suspect a memory exists will simply never call a
|
|
98
|
+
* tool. Saying so once, up front, is the whole difference.
|
|
99
|
+
*
|
|
100
|
+
* Kept deliberately short and free of bulk. The obvious move is to inline the
|
|
101
|
+
* profile, standards and lesson list here so a GUI gets everything the
|
|
102
|
+
* launcher injects -- but instructions are paid on every connection whether
|
|
103
|
+
* used or not, and clients are free to truncate or ignore the field. A cheap
|
|
104
|
+
* nudge plus one get_context call is both smaller and more robust than a
|
|
105
|
+
* large block that may be silently dropped.
|
|
106
|
+
*/
|
|
107
|
+
const INSTRUCTIONS = [
|
|
108
|
+
"This is the user's persistent memory across every AI tool they use: past sessions, project decisions, and lessons learned the hard way.",
|
|
109
|
+
'',
|
|
110
|
+
'Before answering anything about their work, call get_context. It returns their profile, standards, the current project note, and what the last session concluded.',
|
|
111
|
+
'Before solving a problem, call search_memory -- they may have solved it already, and repeating a solved mistake is the failure this vault exists to prevent. Search broadly first; too specific a first query is the usual way to miss something.',
|
|
112
|
+
'',
|
|
113
|
+
'Write back. A session that only reads leaves nothing behind, and the next one starts cold:',
|
|
114
|
+
'- add_note for what happened, decided, or broke during this session.',
|
|
115
|
+
'- add_lesson for something worth recalling in a DIFFERENT project later. Not project trivia -- the transferable part.',
|
|
116
|
+
'',
|
|
117
|
+
'If they ask to see, open or browse their memory rather than search it, call open_graph.',
|
|
118
|
+
].join('\n');
|
|
119
|
+
|
|
120
|
+
// Descriptions stay terse on purpose. Every schema below is re-sent on each
|
|
121
|
+
// turn, so prose here is a recurring cost: measured at ~380 tokens for four
|
|
122
|
+
// verbosely-described tools. Behavior guidance belongs in INSTRUCTIONS, said
|
|
123
|
+
// once, rather than restated inside each tool.
|
|
124
|
+
const TOOLS = [
|
|
125
|
+
{
|
|
126
|
+
name: 'search_memory',
|
|
127
|
+
description: 'Search all past sessions, project notes and lessons. Literal, case-insensitive, newest first.',
|
|
128
|
+
inputSchema: {
|
|
129
|
+
type: 'object',
|
|
130
|
+
properties: {
|
|
131
|
+
term: { type: 'string', description: 'Text to find. Not a regex.' },
|
|
132
|
+
project: { type: 'string', description: 'Optional: one project only.' },
|
|
133
|
+
},
|
|
134
|
+
required: ['term'],
|
|
135
|
+
},
|
|
136
|
+
},
|
|
137
|
+
{
|
|
138
|
+
name: 'get_context',
|
|
139
|
+
description: 'The user\'s profile, standards, current project note, last session digest, and known lesson topics.',
|
|
140
|
+
inputSchema: {
|
|
141
|
+
type: 'object',
|
|
142
|
+
properties: { project: { type: 'string', description: 'Defaults to the active project.' } },
|
|
143
|
+
},
|
|
144
|
+
},
|
|
145
|
+
{
|
|
146
|
+
name: 'read_note',
|
|
147
|
+
description: 'Read one vault note by path.',
|
|
148
|
+
inputSchema: {
|
|
149
|
+
type: 'object',
|
|
150
|
+
properties: { path: { type: 'string', description: 'Absolute, or relative to the vault root.' } },
|
|
151
|
+
required: ['path'],
|
|
152
|
+
},
|
|
153
|
+
},
|
|
154
|
+
{
|
|
155
|
+
name: 'add_note',
|
|
156
|
+
description: 'Append a timestamped note to today\'s session log. Use for what happened or was decided.',
|
|
157
|
+
inputSchema: {
|
|
158
|
+
type: 'object',
|
|
159
|
+
properties: { text: { type: 'string', description: 'What to record.' } },
|
|
160
|
+
required: ['text'],
|
|
161
|
+
},
|
|
162
|
+
},
|
|
163
|
+
{
|
|
164
|
+
name: 'open_graph',
|
|
165
|
+
description: 'Open the vault as a browsable graph in the user\'s browser. Use when they ask to see, open or browse their memory.',
|
|
166
|
+
inputSchema: { type: 'object', properties: {} },
|
|
167
|
+
},
|
|
168
|
+
{
|
|
169
|
+
name: 'add_lesson',
|
|
170
|
+
description: 'Record a problem and its solution as a cross-project lesson. Use only for something that will matter in a different project.',
|
|
171
|
+
inputSchema: {
|
|
172
|
+
type: 'object',
|
|
173
|
+
properties: {
|
|
174
|
+
topic: { type: 'string', description: 'Short slug, e.g. rate-limiting.' },
|
|
175
|
+
problem: { type: 'string', description: 'What went wrong.' },
|
|
176
|
+
solution: { type: 'string', description: 'What fixed it.' },
|
|
177
|
+
},
|
|
178
|
+
required: ['topic', 'problem', 'solution'],
|
|
179
|
+
},
|
|
180
|
+
},
|
|
181
|
+
];
|
|
182
|
+
|
|
183
|
+
/** Dispatch a tool call to the zsh function that owns its behavior. */
|
|
184
|
+
function callTool(name, args = {}) {
|
|
185
|
+
switch (name) {
|
|
186
|
+
case 'search_memory':
|
|
187
|
+
return zsh(`ai-mem-search ${q(args.term)} ${args.project ? q(args.project) : ''}`);
|
|
188
|
+
case 'get_context':
|
|
189
|
+
return zsh(`ai-context ${args.project ? q(args.project) : ''}`);
|
|
190
|
+
// ai-note and ai-lesson both push the vault themselves, so a GUI write is
|
|
191
|
+
// committed and backed up exactly like a terminal one -- no separate step
|
|
192
|
+
// for the model to forget.
|
|
193
|
+
case 'add_note':
|
|
194
|
+
if (!args.text) return { ok: false, text: 'text is required' };
|
|
195
|
+
return zsh(`ai-note ${q(args.text)}`);
|
|
196
|
+
case 'add_lesson':
|
|
197
|
+
if (!args.topic || !args.problem || !args.solution) {
|
|
198
|
+
return { ok: false, text: 'topic, problem and solution are all required' };
|
|
199
|
+
}
|
|
200
|
+
return zsh(`ai-lesson ${q(args.topic)} ${q(args.problem)} ${q(args.solution)}`);
|
|
201
|
+
// Detached and unref'd: the viewer has to outlive this call, and an MCP
|
|
202
|
+
// tool that blocks until a server exits would hang the client forever.
|
|
203
|
+
case 'open_graph': {
|
|
204
|
+
const bin = join(__dirname, 'ai-mem-serve.js');
|
|
205
|
+
const port = process.env.AI_MEM_PORT || '7777';
|
|
206
|
+
try {
|
|
207
|
+
spawn(process.execPath, [bin, port], {
|
|
208
|
+
stdio: 'ignore', detached: true, env: { ...process.env, AI_MEM_ROOT: VAULT },
|
|
209
|
+
}).unref();
|
|
210
|
+
} catch (e) {
|
|
211
|
+
return { ok: false, text: 'could not start the viewer: ' + e.message };
|
|
212
|
+
}
|
|
213
|
+
return { ok: true, text: 'Opened the memory graph at http://127.0.0.1:' + port + ' (a browser tab should be opening).' };
|
|
214
|
+
}
|
|
215
|
+
case 'read_note': {
|
|
216
|
+
const p = insideVault(args.path || '');
|
|
217
|
+
if (!p) return { ok: false, text: `refused: ${args.path} is not inside the vault` };
|
|
218
|
+
if (!existsSync(p)) return { ok: false, text: `not found: ${args.path}` };
|
|
219
|
+
return { ok: true, text: readFileSync(p, 'utf8') };
|
|
220
|
+
}
|
|
221
|
+
default:
|
|
222
|
+
return { ok: false, text: `unknown tool: ${name}` };
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** Write one JSON-RPC message. stdout carries protocol only; logs go to stderr. */
|
|
227
|
+
const send = (msg) => process.stdout.write(JSON.stringify(msg) + '\n');
|
|
228
|
+
|
|
229
|
+
function handle(req) {
|
|
230
|
+
const { id, method, params } = req;
|
|
231
|
+
// Notifications have no id and must never be answered.
|
|
232
|
+
if (id === undefined) return;
|
|
233
|
+
|
|
234
|
+
if (method === 'initialize') {
|
|
235
|
+
return send({
|
|
236
|
+
jsonrpc: '2.0',
|
|
237
|
+
id,
|
|
238
|
+
result: {
|
|
239
|
+
// Echo the client's protocol version when it sends one: a server that
|
|
240
|
+
// hardcodes its own is rejected outright by clients on a different one.
|
|
241
|
+
protocolVersion: params?.protocolVersion || '2025-06-18',
|
|
242
|
+
capabilities: { tools: {} },
|
|
243
|
+
serverInfo: { name: 'ai-memory', version: VERSION },
|
|
244
|
+
instructions: INSTRUCTIONS,
|
|
245
|
+
},
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
if (method === 'tools/list') return send({ jsonrpc: '2.0', id, result: { tools: TOOLS } });
|
|
249
|
+
if (method === 'tools/call') {
|
|
250
|
+
const { ok, text } = callTool(params?.name, params?.arguments || {});
|
|
251
|
+
// A failed tool call is reported as tool content with isError, not as a
|
|
252
|
+
// JSON-RPC error: the model should see "no matches" and adapt, rather than
|
|
253
|
+
// the client treating a normal empty result as a transport fault.
|
|
254
|
+
return send({ jsonrpc: '2.0', id, result: { content: [{ type: 'text', text }], isError: !ok } });
|
|
255
|
+
}
|
|
256
|
+
send({ jsonrpc: '2.0', id, error: { code: -32601, message: `method not found: ${method}` } });
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
readline.createInterface({ input: process.stdin }).on('line', (line) => {
|
|
260
|
+
if (!line.trim()) return;
|
|
261
|
+
let req;
|
|
262
|
+
try {
|
|
263
|
+
req = JSON.parse(line);
|
|
264
|
+
} catch {
|
|
265
|
+
return send({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'parse error' } });
|
|
266
|
+
}
|
|
267
|
+
try {
|
|
268
|
+
handle(req);
|
|
269
|
+
} catch (e) {
|
|
270
|
+
if (req.id !== undefined) {
|
|
271
|
+
send({ jsonrpc: '2.0', id: req.id, error: { code: -32603, message: String(e && e.message) } });
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
});
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* ai-mem-serve: browse the vault as a graph in a browser.
|
|
4
|
+
*
|
|
5
|
+
* `ai-mem-search` answers a question you already knew to ask. This is for the
|
|
6
|
+
* other case -- seeing what is in there at all, and which notes turned out to
|
|
7
|
+
* be connected. The vault is an OKF bundle: markdown files with a `type` in
|
|
8
|
+
* frontmatter and wikilinks between them, which is already a graph. This only
|
|
9
|
+
* draws it.
|
|
10
|
+
*
|
|
11
|
+
* Serves three routes and nothing else:
|
|
12
|
+
* / the viewer
|
|
13
|
+
* /api/graph nodes and edges, built by scanning the vault
|
|
14
|
+
* /api/note one note's raw markdown
|
|
15
|
+
*
|
|
16
|
+
* Binds to 127.0.0.1 only. The vault holds private project history and
|
|
17
|
+
* production detail; a viewer for it has no business being reachable from the
|
|
18
|
+
* network.
|
|
19
|
+
*
|
|
20
|
+
* Zero dependencies, like the rest of the package.
|
|
21
|
+
*
|
|
22
|
+
* Usage: ai-mem-serve [port] [--no-open]
|
|
23
|
+
*
|
|
24
|
+
* Opens a browser at the URL by default, and is idempotent: asked twice, the
|
|
25
|
+
* second call finds the first still listening and just opens the tab. The
|
|
26
|
+
* usual caller is an agent acting on "open my memory", which should not have
|
|
27
|
+
* to check whether it is already running, nor report a port collision as a
|
|
28
|
+
* failure.
|
|
29
|
+
*/
|
|
30
|
+
'use strict';
|
|
31
|
+
|
|
32
|
+
const http = require('node:http');
|
|
33
|
+
const { spawn } = require('node:child_process');
|
|
34
|
+
const { readFileSync, readdirSync, statSync, existsSync, realpathSync } = require('node:fs');
|
|
35
|
+
const { join, resolve, relative, basename, extname } = require('node:path');
|
|
36
|
+
const { homedir } = require('node:os');
|
|
37
|
+
|
|
38
|
+
const VAULT = process.env.AI_MEM_ROOT || join(homedir(), '.ai-memory', '_Ai_Memory');
|
|
39
|
+
const ARGS = process.argv.slice(2);
|
|
40
|
+
const NO_OPEN = ARGS.includes('--no-open');
|
|
41
|
+
const PORT = Number(ARGS.find((a) => /^\d+$/.test(a)) || process.env.AI_MEM_PORT || 7777);
|
|
42
|
+
const VIEWER = join(__dirname, '..', 'web', 'viewer.html');
|
|
43
|
+
|
|
44
|
+
/** Recursively collect every .md file in the vault, skipping dotfiles and templates. */
|
|
45
|
+
function walk(dir, out = []) {
|
|
46
|
+
let entries;
|
|
47
|
+
try {
|
|
48
|
+
entries = readdirSync(dir, { withFileTypes: true });
|
|
49
|
+
} catch {
|
|
50
|
+
return out;
|
|
51
|
+
}
|
|
52
|
+
for (const e of entries) {
|
|
53
|
+
if (e.name.startsWith('.')) continue;
|
|
54
|
+
const p = join(dir, e.name);
|
|
55
|
+
if (e.isDirectory()) walk(p, out);
|
|
56
|
+
else if (extname(e.name) === '.md' && !e.name.endsWith('_template.md')) out.push(p);
|
|
57
|
+
}
|
|
58
|
+
return out;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Pull the frontmatter block into a flat object.
|
|
63
|
+
*
|
|
64
|
+
* Hand-rolled rather than pulled in as a dependency: the vault's frontmatter
|
|
65
|
+
* is flat key/value plus the occasional inline list, which is a few lines of
|
|
66
|
+
* parsing, and a YAML library would be this package's only dependency.
|
|
67
|
+
*/
|
|
68
|
+
function frontmatter(text) {
|
|
69
|
+
if (!text.startsWith('---')) return {};
|
|
70
|
+
const end = text.indexOf('\n---', 3);
|
|
71
|
+
if (end === -1) return {};
|
|
72
|
+
const out = {};
|
|
73
|
+
for (const line of text.slice(4, end).split('\n')) {
|
|
74
|
+
const m = line.match(/^([A-Za-z_][\w-]*):\s*(.*)$/);
|
|
75
|
+
if (!m) continue;
|
|
76
|
+
let v = m[2].trim().replace(/^["']|["']$/g, '');
|
|
77
|
+
if (v.startsWith('[') && v.endsWith(']')) {
|
|
78
|
+
v = v.slice(1, -1).split(',').map((x) => x.trim().replace(/^["']|["']$/g, '')).filter(Boolean);
|
|
79
|
+
}
|
|
80
|
+
out[m[1]] = v;
|
|
81
|
+
}
|
|
82
|
+
return out;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** First H1, else the filename -- what a human would call this note. */
|
|
86
|
+
function titleOf(text, path) {
|
|
87
|
+
const h1 = text.match(/^#\s+(.+)$/m);
|
|
88
|
+
return (h1 && h1[1].trim()) || basename(path, '.md');
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const LINK_RE = /\[\[([^\]|#]+)/g;
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Build the graph.
|
|
95
|
+
*
|
|
96
|
+
* Edges come from wikilinks, resolved by basename because that is how
|
|
97
|
+
* Obsidian resolves them and how the vault is actually written. A link with
|
|
98
|
+
* no matching note is dropped rather than drawn to a phantom -- OKF requires
|
|
99
|
+
* consumers to tolerate links that do not resolve.
|
|
100
|
+
*/
|
|
101
|
+
function buildGraph() {
|
|
102
|
+
const files = walk(VAULT);
|
|
103
|
+
const nodes = [];
|
|
104
|
+
const byBasename = new Map();
|
|
105
|
+
|
|
106
|
+
for (const f of files) {
|
|
107
|
+
let text;
|
|
108
|
+
try {
|
|
109
|
+
text = readFileSync(f, 'utf8');
|
|
110
|
+
} catch {
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
const fm = frontmatter(text);
|
|
114
|
+
const node = {
|
|
115
|
+
id: relative(VAULT, f),
|
|
116
|
+
title: fm.title || titleOf(text, f),
|
|
117
|
+
type: fm.type || 'untyped',
|
|
118
|
+
tags: Array.isArray(fm.tags) ? fm.tags : fm.tags ? [fm.tags] : [],
|
|
119
|
+
description: fm.description || '',
|
|
120
|
+
resource: fm.resource || '',
|
|
121
|
+
mtime: (() => {
|
|
122
|
+
try {
|
|
123
|
+
return statSync(f).mtimeMs;
|
|
124
|
+
} catch {
|
|
125
|
+
return 0;
|
|
126
|
+
}
|
|
127
|
+
})(),
|
|
128
|
+
links: [...text.matchAll(LINK_RE)].map((m) => m[1].trim()),
|
|
129
|
+
};
|
|
130
|
+
nodes.push(node);
|
|
131
|
+
// First writer wins: a duplicate basename is ambiguous in Obsidian too.
|
|
132
|
+
if (!byBasename.has(basename(f, '.md'))) byBasename.set(basename(f, '.md'), node.id);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const seen = new Set();
|
|
136
|
+
const edges = [];
|
|
137
|
+
for (const n of nodes) {
|
|
138
|
+
for (const link of n.links) {
|
|
139
|
+
const target = byBasename.get(link);
|
|
140
|
+
if (!target || target === n.id) continue;
|
|
141
|
+
const key = n.id + ' -> ' + target;
|
|
142
|
+
if (seen.has(key)) continue;
|
|
143
|
+
seen.add(key);
|
|
144
|
+
edges.push({ source: n.id, target });
|
|
145
|
+
}
|
|
146
|
+
delete n.links;
|
|
147
|
+
}
|
|
148
|
+
return { vault: VAULT, nodes, edges };
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Resolve a note path, refusing anything that escapes the vault. */
|
|
152
|
+
function insideVault(p) {
|
|
153
|
+
try {
|
|
154
|
+
const root = realpathSync(VAULT);
|
|
155
|
+
const target = realpathSync(resolve(join(VAULT, p)));
|
|
156
|
+
return target === root || target.startsWith(root + '/') ? target : null;
|
|
157
|
+
} catch {
|
|
158
|
+
return null;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const json = (res, code, body) => {
|
|
163
|
+
res.writeHead(code, { 'content-type': 'application/json; charset=utf-8' });
|
|
164
|
+
res.end(JSON.stringify(body));
|
|
165
|
+
};
|
|
166
|
+
|
|
167
|
+
const server = http.createServer((req, res) => {
|
|
168
|
+
const url = new URL(req.url, 'http://localhost');
|
|
169
|
+
|
|
170
|
+
if (url.pathname === '/') {
|
|
171
|
+
if (!existsSync(VIEWER)) return json(res, 500, { error: 'viewer.html is missing from the package' });
|
|
172
|
+
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
|
|
173
|
+
return res.end(readFileSync(VIEWER));
|
|
174
|
+
}
|
|
175
|
+
if (url.pathname === '/api/graph') return json(res, 200, buildGraph());
|
|
176
|
+
if (url.pathname === '/api/note') {
|
|
177
|
+
const rel = url.searchParams.get('path') || '';
|
|
178
|
+
const p = insideVault(rel);
|
|
179
|
+
if (!p) return json(res, 403, { error: 'path is not inside the vault' });
|
|
180
|
+
if (!existsSync(p)) return json(res, 404, { error: 'not found' });
|
|
181
|
+
return json(res, 200, { path: rel, text: readFileSync(p, 'utf8') });
|
|
182
|
+
}
|
|
183
|
+
json(res, 404, { error: 'not found' });
|
|
184
|
+
});
|
|
185
|
+
|
|
186
|
+
if (!existsSync(VAULT)) {
|
|
187
|
+
console.error('ai-mem-serve: no vault at ' + VAULT + '. Set AI_MEM_ROOT.');
|
|
188
|
+
process.exit(1);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Hand the URL to the desktop. Failure is ignored on purpose: a headless box
|
|
193
|
+
* or a locked-down desktop has no opener, and that is not a reason for the
|
|
194
|
+
* server itself to fail -- the URL is printed either way.
|
|
195
|
+
*/
|
|
196
|
+
function openBrowser(url) {
|
|
197
|
+
if (NO_OPEN) return;
|
|
198
|
+
const cmd = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'start' : 'xdg-open';
|
|
199
|
+
try {
|
|
200
|
+
spawn(cmd, [url], { stdio: 'ignore', detached: true, shell: process.platform === 'win32' }).unref();
|
|
201
|
+
} catch {
|
|
202
|
+
/* no opener; the printed URL is the fallback */
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// Loopback only, deliberately. See the header note.
|
|
207
|
+
server.listen(PORT, '127.0.0.1', () => {
|
|
208
|
+
const g = buildGraph();
|
|
209
|
+
const url = 'http://127.0.0.1:' + server.address().port;
|
|
210
|
+
console.log('ai-mem-serve: ' + g.nodes.length + ' notes, ' + g.edges.length + ' links');
|
|
211
|
+
console.log(' ' + url);
|
|
212
|
+
openBrowser(url);
|
|
213
|
+
});
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* A port already in use is the expected case, not an error: it almost always
|
|
217
|
+
* means a previous "open my memory" is still serving. Confirm it is this
|
|
218
|
+
* server rather than something unrelated, then open the tab and exit clean.
|
|
219
|
+
* Reporting EADDRINUSE would make an agent believe the request failed.
|
|
220
|
+
*/
|
|
221
|
+
server.on('error', (err) => {
|
|
222
|
+
if (err.code !== 'EADDRINUSE') {
|
|
223
|
+
console.error('ai-mem-serve: ' + err.message);
|
|
224
|
+
process.exit(1);
|
|
225
|
+
}
|
|
226
|
+
const url = 'http://127.0.0.1:' + PORT;
|
|
227
|
+
http.get(url + '/api/graph', (res) => {
|
|
228
|
+
if (res.statusCode !== 200) return bail();
|
|
229
|
+
res.resume();
|
|
230
|
+
console.log('ai-mem-serve: already running');
|
|
231
|
+
console.log(' ' + url);
|
|
232
|
+
openBrowser(url);
|
|
233
|
+
process.exit(0);
|
|
234
|
+
}).on('error', bail);
|
|
235
|
+
|
|
236
|
+
function bail() {
|
|
237
|
+
console.error('ai-mem-serve: port ' + PORT + ' is in use by something else. Pass a different port.');
|
|
238
|
+
process.exit(1);
|
|
239
|
+
}
|
|
240
|
+
});
|
package/package.json
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "create-ai-memory",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.14.0",
|
|
4
4
|
"description": "Persistent, agent-agnostic session memory for AI coding CLIs (Claude Code, Codex, Gemini, Cursor, opencode). One Markdown vault, any agent.",
|
|
5
5
|
"bin": {
|
|
6
|
-
"create-ai-memory": "bin/create-ai-memory.js"
|
|
6
|
+
"create-ai-memory": "bin/create-ai-memory.js",
|
|
7
|
+
"ai-mem-mcp": "bin/ai-mem-mcp.js",
|
|
8
|
+
"ai-mem-serve": "bin/ai-mem-serve.js"
|
|
7
9
|
},
|
|
8
10
|
"scripts": {
|
|
9
11
|
"test": "zsh tests/run.sh",
|
|
@@ -16,6 +18,7 @@
|
|
|
16
18
|
"files": [
|
|
17
19
|
"bin/",
|
|
18
20
|
"shell/",
|
|
21
|
+
"web/",
|
|
19
22
|
"hooks/",
|
|
20
23
|
"vault-template/",
|
|
21
24
|
"install.sh",
|
|
@@ -23,16 +26,17 @@
|
|
|
23
26
|
"LICENSE"
|
|
24
27
|
],
|
|
25
28
|
"keywords": [
|
|
29
|
+
"agent",
|
|
26
30
|
"ai",
|
|
27
|
-
"memory",
|
|
28
31
|
"claude",
|
|
32
|
+
"cli",
|
|
29
33
|
"codex",
|
|
30
|
-
"gemini",
|
|
31
34
|
"cursor",
|
|
32
|
-
"
|
|
33
|
-
"
|
|
34
|
-
"
|
|
35
|
+
"gemini",
|
|
36
|
+
"mcp",
|
|
37
|
+
"memory",
|
|
35
38
|
"obsidian",
|
|
39
|
+
"opencode",
|
|
36
40
|
"zsh"
|
|
37
41
|
],
|
|
38
42
|
"homepage": "https://github.com/rambaarde/create-ai-memory#readme",
|
package/shell/adapters.zsh
CHANGED
|
@@ -1,22 +1,22 @@
|
|
|
1
1
|
# Agent launch adapters for ai-mem.
|
|
2
2
|
#
|
|
3
|
-
# One function per agent:
|
|
3
|
+
# One function per agent: __ai_adapter_<name>. It receives:
|
|
4
4
|
# $1 memory_prompt — assembled vault context + session-mode block
|
|
5
5
|
# $2 mode_block — just the session-mode instructions (may be empty)
|
|
6
6
|
# $3… extra CLI args — anything passed to <name>-start (e.g. files to open)
|
|
7
7
|
#
|
|
8
|
-
# Add a new agent (opencode, aider, …) by defining
|
|
8
|
+
# Add a new agent (opencode, aider, …) by defining __ai_adapter_<name> here and
|
|
9
9
|
# listing <name> in AI_MEM_AGENTS (see ai-mem.zsh). No core edits needed.
|
|
10
10
|
|
|
11
11
|
# Codex: --add-dir grants read access to the vault; prompt is positional.
|
|
12
|
-
|
|
12
|
+
__ai_adapter_codex() {
|
|
13
13
|
local memory_prompt="$1"
|
|
14
14
|
codex --add-dir "$AI_MEM_ROOT" "$memory_prompt"
|
|
15
15
|
}
|
|
16
16
|
|
|
17
17
|
# Claude Code: --add-dir is variadic, so the prompt must come FIRST or it gets
|
|
18
18
|
# swallowed as a bogus directory and Claude starts with no initial prompt.
|
|
19
|
-
|
|
19
|
+
__ai_adapter_claude() {
|
|
20
20
|
local memory_prompt="$1" mode_block="$2"
|
|
21
21
|
if [[ -n "$mode_block" ]]; then
|
|
22
22
|
claude "$memory_prompt" --add-dir "$AI_MEM_ROOT" --append-system-prompt "$mode_block"
|
|
@@ -26,15 +26,26 @@ _ai_adapter_claude() {
|
|
|
26
26
|
}
|
|
27
27
|
|
|
28
28
|
# Gemini CLI: --include-directories for vault access, -i for the initial prompt.
|
|
29
|
-
|
|
29
|
+
__ai_adapter_gemini() {
|
|
30
30
|
local memory_prompt="$1"
|
|
31
31
|
gemini --include-directories "$AI_MEM_ROOT" -i "$memory_prompt"
|
|
32
32
|
}
|
|
33
33
|
|
|
34
|
-
# Cursor
|
|
35
|
-
#
|
|
36
|
-
#
|
|
37
|
-
|
|
34
|
+
# Cursor ships two entry points. `cursor-agent` is the CLI and takes the
|
|
35
|
+
# prompt positionally, so it gets the vault context like every other agent.
|
|
36
|
+
# `cursor` is the GUI, which has no prompt path -- launching it drops the
|
|
37
|
+
# memory prompt entirely, so it is a fallback rather than the target.
|
|
38
|
+
#
|
|
39
|
+
# Either way the session's skill choices are persisted as a managed
|
|
40
|
+
# always-apply rule, rewritten each launch and cleared when nothing is
|
|
41
|
+
# selected: cursor-agent has no --append-system-prompt equivalent, so the
|
|
42
|
+
# rule file is the only channel for the mode block.
|
|
43
|
+
#
|
|
44
|
+
# --workspace is deliberately not passed. It sets the working directory,
|
|
45
|
+
# which already is the project being worked on, and it is not an --add-dir
|
|
46
|
+
# equivalent -- the vault reaches Cursor through the absolute note paths
|
|
47
|
+
# inlined in the prompt.
|
|
48
|
+
__ai_adapter_cursor() {
|
|
38
49
|
local memory_prompt="$1" mode_block="$2"
|
|
39
50
|
shift 2
|
|
40
51
|
local cursor_rule="$HOME/.cursor/rules/_ai-session.mdc"
|
|
@@ -52,7 +63,9 @@ _ai_adapter_cursor() {
|
|
|
52
63
|
else
|
|
53
64
|
rm -f "$cursor_rule"
|
|
54
65
|
fi
|
|
55
|
-
if command -v cursor >/dev/null 2>&1; then
|
|
66
|
+
if command -v cursor-agent >/dev/null 2>&1; then
|
|
67
|
+
cursor-agent "$memory_prompt" "$@"
|
|
68
|
+
elif command -v cursor >/dev/null 2>&1; then
|
|
56
69
|
cursor "$@"
|
|
57
70
|
else
|
|
58
71
|
open -a Cursor
|
|
@@ -62,14 +75,14 @@ _ai_adapter_cursor() {
|
|
|
62
75
|
# opencode (sst/opencode): the TUI seeds its first message from --prompt. It has
|
|
63
76
|
# no --add-dir, so vault access rides on the inlined profile/standards in the
|
|
64
77
|
# prompt plus the absolute note paths the agent can read on demand.
|
|
65
|
-
|
|
78
|
+
__ai_adapter_opencode() {
|
|
66
79
|
local memory_prompt="$1"
|
|
67
80
|
opencode --prompt "$memory_prompt"
|
|
68
81
|
}
|
|
69
82
|
|
|
70
83
|
# --- Example: add another agent by defining its adapter and listing it in
|
|
71
84
|
# AI_MEM_AGENTS. aider takes the initial instruction via --message:
|
|
72
|
-
#
|
|
85
|
+
# __ai_adapter_aider() {
|
|
73
86
|
# local memory_prompt="$1"
|
|
74
87
|
# aider --message "$memory_prompt"
|
|
75
88
|
# }
|