create-ai-memory 0.13.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 +105 -1
- 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 +17 -4
- package/shell/ai-mem.zsh +1 -0
- package/web/viewer.html +666 -0
package/README.md
CHANGED
|
@@ -204,6 +204,8 @@ off last time.
|
|
|
204
204
|
- [Open Knowledge Format](#open-knowledge-format)
|
|
205
205
|
- [Add another agent](#add-another-agent)
|
|
206
206
|
- [Integrations](#integrations)
|
|
207
|
+
- [Graph view](#graph-view)
|
|
208
|
+
- [GUI clients (MCP)](#gui-clients-mcp)
|
|
207
209
|
- [Configuration](#configuration)
|
|
208
210
|
|
|
209
211
|
</td>
|
|
@@ -226,7 +228,7 @@ off last time.
|
|
|
226
228
|
|
|
227
229
|
| | |
|
|
228
230
|
|---|---|
|
|
229
|
-
| **Cross-agent memory** | One vault serves Claude Code, Codex, Gemini, Cursor, and opencode. Context earned in one reaches the next. |
|
|
231
|
+
| **Cross-agent memory** | One vault serves Claude Code, Codex, Gemini, Cursor, and opencode — and GUI clients like Claude Desktop through an MCP server. Context earned in one reaches the next. |
|
|
230
232
|
| **Automatic carryover** | A Stop hook writes the branch, the commits you made, and uncommitted changes into the session log, so tomorrow's run resumes where today's ended. |
|
|
231
233
|
| **Per-project context** | Each git repo gets its own note for purpose, architecture, and decisions, injected only for that project. |
|
|
232
234
|
| **Your rules, everywhere** | A global profile and standards note ride along in every session, on every project. |
|
|
@@ -334,6 +336,7 @@ optional. Set `AI_MEM_ROOT` in `~/.zshrc` first if you do not want the default
|
|
|
334
336
|
| `ai-lesson <topic-slug> <problem> <solution>` | Append a dated Problem/Solution entry to a cross-project `_lessons/<topic-slug>.md` -- decisions, mistakes, solutions worth recalling outside the current project |
|
|
335
337
|
| `ai-mem-lint [--fix]` | Check the vault's links: orphaned session logs, dangling `previous` links, unreferenced project notes, and notes missing the `type:` field. `--fix` backfills `type:` into session logs written before the field existed |
|
|
336
338
|
| `ai-mem-search <term> [project]` | Case-insensitive literal search across the vault (or one project's logs), newest match first. Paths print relative to a root stated once in the header. Output is capped (`AI_MEM_SEARCH_LIMIT`, default 40) with an explicit `N hidden` notice, because the usual caller is an agent with a finite context window. Also resolves any `[[wikilink]]` on a matched line to its project note -- one hop out along the graph, always on, not a flag to remember |
|
|
339
|
+
| `ai-mem-serve [port] [--no-open]` | Open the vault as a browsable graph on `127.0.0.1`. Agents run this for you when you ask to see your memory (see [Graph view](#graph-view)) |
|
|
337
340
|
| `ai-mem-vault-backup` | Commit and push the vault if it's git-backed. `ai-note`/`ai-lesson` already call this; use it directly after editing a session log or project note by hand |
|
|
338
341
|
|
|
339
342
|
Project is auto-resolved from the current git repo; pass a name to override.
|
|
@@ -675,6 +678,11 @@ Launchers are not hardcoded. Each agent is one small adapter, and the
|
|
|
675
678
|
```
|
|
676
679
|
3. `aider-start` now exists. No core edits.
|
|
677
680
|
|
|
681
|
+
`cursor-start` targets `cursor-agent`, Cursor's CLI, which takes the prompt
|
|
682
|
+
positionally. If only the `cursor` GUI is installed it falls back to opening
|
|
683
|
+
that instead -- the GUI has no prompt path, so the session's skills still
|
|
684
|
+
arrive via the managed rule file but the vault context does not.
|
|
685
|
+
|
|
678
686
|
Name private helpers with **two** leading underscores (`__ai_adapter_aider`,
|
|
679
687
|
not `_ai_adapter_aider`). Claude Code replays a snapshot of your interactive
|
|
680
688
|
shell for every command it runs, and that snapshot drops single-underscore
|
|
@@ -684,6 +692,102 @@ an agent-run command.
|
|
|
684
692
|
|
|
685
693
|
## Integrations
|
|
686
694
|
|
|
695
|
+
### Graph view
|
|
696
|
+
|
|
697
|
+
`ai-mem-search` answers a question you already knew to ask. This is for the
|
|
698
|
+
other one — what is in there at all, and which notes turned out to be
|
|
699
|
+
connected.
|
|
700
|
+
|
|
701
|
+
You should not usually have to run this. **Ask the agent** — "open my memory",
|
|
702
|
+
"show me my context" — and it will: the launch prompt tells terminal agents
|
|
703
|
+
the viewer exists, and GUI clients get an `open_graph` tool over MCP. Running
|
|
704
|
+
it by hand stays available:
|
|
705
|
+
|
|
706
|
+
```sh
|
|
707
|
+
ai-mem-serve # opens a browser at http://127.0.0.1:7777
|
|
708
|
+
ai-mem-serve 8080 --no-open
|
|
709
|
+
```
|
|
710
|
+
|
|
711
|
+
Asked twice, the second call finds the first still listening and just opens
|
|
712
|
+
the tab. An agent should not have to check whether it is already running, and
|
|
713
|
+
a port collision with **its own** server is not a failure worth reporting —
|
|
714
|
+
though a port held by something else still is.
|
|
715
|
+
|
|
716
|
+

|
|
717
|
+
|
|
718
|
+
Nothing here is a separate database. The vault is already a graph — notes
|
|
719
|
+
carrying a `type` in frontmatter with `[[wikilinks]]` between them — so this
|
|
720
|
+
only draws what is on disk.
|
|
721
|
+
|
|
722
|
+
- **Nodes are coloured by `type`** and sized by how many notes link to them, so
|
|
723
|
+
a project that has accumulated forty sessions looks like the hub it is.
|
|
724
|
+
- **Selecting a note** dims everything it is not connected to, shows the note
|
|
725
|
+
rendered beside the graph, and lists what it links to.
|
|
726
|
+
- **Durable knowledge** is the default view. Session logs usually outnumber
|
|
727
|
+
everything else several times over and all point at their project, which
|
|
728
|
+
buries the projects and lessons inside a hairball. Switch to *Everything* to
|
|
729
|
+
see them.
|
|
730
|
+
- **Search** and the legend both filter; `/` focuses the search box.
|
|
731
|
+
|
|
732
|
+
Bound to `127.0.0.1` only, deliberately. The vault holds project history and
|
|
733
|
+
operational detail, and a viewer for it has no business being reachable from
|
|
734
|
+
the network. Zero dependencies — the layout is a small force simulation rather
|
|
735
|
+
than a charting library, so it works with no network at all.
|
|
736
|
+
|
|
737
|
+
### GUI clients (MCP)
|
|
738
|
+
|
|
739
|
+
The `*-start` launchers reach an agent by injecting the vault into its opening
|
|
740
|
+
prompt. **A GUI opened from the Dock never runs one** — there is no daemon and
|
|
741
|
+
no background service, so Claude Desktop and the Cursor GUI would otherwise
|
|
742
|
+
see nothing.
|
|
743
|
+
|
|
744
|
+
`ai-mem-mcp` is the channel for those. Register it once:
|
|
745
|
+
|
|
746
|
+
**Claude Desktop** — `~/Library/Application Support/Claude/claude_desktop_config.json`
|
|
747
|
+
|
|
748
|
+
```json
|
|
749
|
+
{
|
|
750
|
+
"mcpServers": {
|
|
751
|
+
"ai-memory": {
|
|
752
|
+
"command": "ai-mem-mcp",
|
|
753
|
+
"env": { "AI_MEM_ROOT": "/absolute/path/to/your/_Ai_Memory" }
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
```
|
|
758
|
+
|
|
759
|
+
**Cursor** — `~/.cursor/mcp.json`, same shape.
|
|
760
|
+
|
|
761
|
+
Six tools, read **and** write, so a GUI session is not a dead end:
|
|
762
|
+
`search_memory`, `get_context`, `read_note`, `add_note`, `add_lesson`, and
|
|
763
|
+
`open_graph` (which launches the [graph view](#graph-view) for them). Each
|
|
764
|
+
shells out to the same zsh functions the CLI uses, so there is one
|
|
765
|
+
implementation of the rules rather than a copy that drifts -- a note written
|
|
766
|
+
from Claude Desktop is committed and pushed exactly like one written in a
|
|
767
|
+
terminal, and is findable by the next session either way.
|
|
768
|
+
|
|
769
|
+
`read_note` compares resolved real paths and refuses anything outside the
|
|
770
|
+
vault.
|
|
771
|
+
|
|
772
|
+
**Making a GUI behave like a launcher.** In a terminal the vault is pushed
|
|
773
|
+
into the agent's opening prompt. Over MCP nothing is pushed, and a model with
|
|
774
|
+
no reason to suspect a memory exists will simply never call a tool. The server
|
|
775
|
+
returns MCP's `instructions` field at startup -- a short standing brief to read
|
|
776
|
+
context first, search before solving, and write back afterwards. That one
|
|
777
|
+
field is the difference between a vault the GUI *could* reach and one it
|
|
778
|
+
actually uses.
|
|
779
|
+
|
|
780
|
+
**On cost.** Tool schemas are re-sent every turn, so their prose is a
|
|
781
|
+
recurring tax; the `instructions` brief is sent once. Behaviour guidance
|
|
782
|
+
therefore lives in `instructions` and the descriptions stay terse. Adding the
|
|
783
|
+
write tools cost nothing per turn as a result: six tools now total ~429
|
|
784
|
+
tokens against ~380 for the original four, with a one-time ~227 for the brief.
|
|
785
|
+
|
|
786
|
+
**Do not register this for a terminal agent.** Claude Code, Codex, Gemini and
|
|
787
|
+
opencode all have a shell and should call `ai-mem-search` directly; wrapping a
|
|
788
|
+
CLI the agent can already run just adds a layer that can go out of date. MCP
|
|
789
|
+
earns its place only where the client has no shell.
|
|
790
|
+
|
|
687
791
|
### Claude Code hooks
|
|
688
792
|
The files live in `hooks/claude/`. Record repo `HEAD` at session start, then on
|
|
689
793
|
exit write an auto block to the log with the branch, commits made this session, and
|
|
@@ -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
|
+
});
|