@hasna/mementos 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +190 -0
- package/README.md +276 -0
- package/dashboard/dist/assets/index-C8vbNL_5.css +1 -0
- package/dashboard/dist/assets/index-Dnhl5e5q.js +270 -0
- package/dashboard/dist/index.html +13 -0
- package/dist/cli/index.d.ts +3 -0
- package/dist/cli/index.d.ts.map +1 -0
- package/dist/cli/index.js +3643 -0
- package/dist/db/agents.d.ts +6 -0
- package/dist/db/agents.d.ts.map +1 -0
- package/dist/db/database.d.ts +10 -0
- package/dist/db/database.d.ts.map +1 -0
- package/dist/db/memories.d.ts +12 -0
- package/dist/db/memories.d.ts.map +1 -0
- package/dist/db/projects.d.ts +6 -0
- package/dist/db/projects.d.ts.map +1 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1174 -0
- package/dist/lib/config.d.ts +5 -0
- package/dist/lib/config.d.ts.map +1 -0
- package/dist/lib/injector.d.ts +31 -0
- package/dist/lib/injector.d.ts.map +1 -0
- package/dist/lib/retention.d.ts +10 -0
- package/dist/lib/retention.d.ts.map +1 -0
- package/dist/lib/search.d.ts +11 -0
- package/dist/lib/search.d.ts.map +1 -0
- package/dist/lib/sync.d.ts +10 -0
- package/dist/lib/sync.d.ts.map +1 -0
- package/dist/mcp/index.d.ts +3 -0
- package/dist/mcp/index.d.ts.map +1 -0
- package/dist/mcp/index.js +5185 -0
- package/dist/server/index.d.ts +7 -0
- package/dist/server/index.d.ts.map +1 -0
- package/dist/server/index.js +1144 -0
- package/dist/types/index.d.ts +158 -0
- package/dist/types/index.d.ts.map +1 -0
- package/package.json +74 -0
|
@@ -0,0 +1,1144 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
// @bun
|
|
3
|
+
|
|
4
|
+
// src/types/index.ts
|
|
5
|
+
class MemoryNotFoundError extends Error {
|
|
6
|
+
constructor(id) {
|
|
7
|
+
super(`Memory not found: ${id}`);
|
|
8
|
+
this.name = "MemoryNotFoundError";
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
class DuplicateMemoryError extends Error {
|
|
13
|
+
constructor(key, scope) {
|
|
14
|
+
super(`Memory already exists with key "${key}" in scope "${scope}"`);
|
|
15
|
+
this.name = "DuplicateMemoryError";
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
class VersionConflictError extends Error {
|
|
19
|
+
expected;
|
|
20
|
+
actual;
|
|
21
|
+
constructor(id, expected, actual) {
|
|
22
|
+
super(`Version conflict for memory ${id}: expected ${expected}, got ${actual}`);
|
|
23
|
+
this.name = "VersionConflictError";
|
|
24
|
+
this.expected = expected;
|
|
25
|
+
this.actual = actual;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// src/db/database.ts
|
|
30
|
+
import { Database } from "bun:sqlite";
|
|
31
|
+
import { existsSync, mkdirSync } from "fs";
|
|
32
|
+
import { dirname, join, resolve } from "path";
|
|
33
|
+
function isInMemoryDb(path) {
|
|
34
|
+
return path === ":memory:" || path.startsWith("file::memory:");
|
|
35
|
+
}
|
|
36
|
+
function findNearestMementosDb(startDir) {
|
|
37
|
+
let dir = resolve(startDir);
|
|
38
|
+
while (true) {
|
|
39
|
+
const candidate = join(dir, ".mementos", "mementos.db");
|
|
40
|
+
if (existsSync(candidate))
|
|
41
|
+
return candidate;
|
|
42
|
+
const parent = dirname(dir);
|
|
43
|
+
if (parent === dir)
|
|
44
|
+
break;
|
|
45
|
+
dir = parent;
|
|
46
|
+
}
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
function findGitRoot(startDir) {
|
|
50
|
+
let dir = resolve(startDir);
|
|
51
|
+
while (true) {
|
|
52
|
+
if (existsSync(join(dir, ".git")))
|
|
53
|
+
return dir;
|
|
54
|
+
const parent = dirname(dir);
|
|
55
|
+
if (parent === dir)
|
|
56
|
+
break;
|
|
57
|
+
dir = parent;
|
|
58
|
+
}
|
|
59
|
+
return null;
|
|
60
|
+
}
|
|
61
|
+
function getDbPath() {
|
|
62
|
+
if (process.env["MEMENTOS_DB_PATH"]) {
|
|
63
|
+
return process.env["MEMENTOS_DB_PATH"];
|
|
64
|
+
}
|
|
65
|
+
const cwd = process.cwd();
|
|
66
|
+
const nearest = findNearestMementosDb(cwd);
|
|
67
|
+
if (nearest)
|
|
68
|
+
return nearest;
|
|
69
|
+
if (process.env["MEMENTOS_DB_SCOPE"] === "project") {
|
|
70
|
+
const gitRoot = findGitRoot(cwd);
|
|
71
|
+
if (gitRoot) {
|
|
72
|
+
return join(gitRoot, ".mementos", "mementos.db");
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
const home = process.env["HOME"] || process.env["USERPROFILE"] || "~";
|
|
76
|
+
return join(home, ".mementos", "mementos.db");
|
|
77
|
+
}
|
|
78
|
+
function ensureDir(filePath) {
|
|
79
|
+
if (isInMemoryDb(filePath))
|
|
80
|
+
return;
|
|
81
|
+
const dir = dirname(resolve(filePath));
|
|
82
|
+
if (!existsSync(dir)) {
|
|
83
|
+
mkdirSync(dir, { recursive: true });
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
var MIGRATIONS = [
|
|
87
|
+
`
|
|
88
|
+
CREATE TABLE IF NOT EXISTS projects (
|
|
89
|
+
id TEXT PRIMARY KEY,
|
|
90
|
+
name TEXT NOT NULL,
|
|
91
|
+
path TEXT UNIQUE NOT NULL,
|
|
92
|
+
description TEXT,
|
|
93
|
+
memory_prefix TEXT,
|
|
94
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
95
|
+
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
96
|
+
);
|
|
97
|
+
|
|
98
|
+
CREATE TABLE IF NOT EXISTS agents (
|
|
99
|
+
id TEXT PRIMARY KEY,
|
|
100
|
+
name TEXT NOT NULL UNIQUE,
|
|
101
|
+
description TEXT,
|
|
102
|
+
role TEXT DEFAULT 'agent',
|
|
103
|
+
metadata TEXT DEFAULT '{}',
|
|
104
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
105
|
+
last_seen_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
106
|
+
);
|
|
107
|
+
|
|
108
|
+
CREATE TABLE IF NOT EXISTS memories (
|
|
109
|
+
id TEXT PRIMARY KEY,
|
|
110
|
+
key TEXT NOT NULL,
|
|
111
|
+
value TEXT NOT NULL,
|
|
112
|
+
category TEXT NOT NULL DEFAULT 'knowledge' CHECK(category IN ('preference', 'fact', 'knowledge', 'history')),
|
|
113
|
+
scope TEXT NOT NULL DEFAULT 'private' CHECK(scope IN ('global', 'shared', 'private')),
|
|
114
|
+
summary TEXT,
|
|
115
|
+
tags TEXT DEFAULT '[]',
|
|
116
|
+
importance INTEGER NOT NULL DEFAULT 5 CHECK(importance >= 1 AND importance <= 10),
|
|
117
|
+
source TEXT NOT NULL DEFAULT 'agent' CHECK(source IN ('user', 'agent', 'system', 'auto', 'imported')),
|
|
118
|
+
status TEXT NOT NULL DEFAULT 'active' CHECK(status IN ('active', 'archived', 'expired')),
|
|
119
|
+
pinned INTEGER NOT NULL DEFAULT 0,
|
|
120
|
+
agent_id TEXT REFERENCES agents(id) ON DELETE SET NULL,
|
|
121
|
+
project_id TEXT REFERENCES projects(id) ON DELETE SET NULL,
|
|
122
|
+
session_id TEXT,
|
|
123
|
+
metadata TEXT DEFAULT '{}',
|
|
124
|
+
access_count INTEGER NOT NULL DEFAULT 0,
|
|
125
|
+
version INTEGER NOT NULL DEFAULT 1,
|
|
126
|
+
expires_at TEXT,
|
|
127
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
128
|
+
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
129
|
+
accessed_at TEXT
|
|
130
|
+
);
|
|
131
|
+
|
|
132
|
+
CREATE TABLE IF NOT EXISTS memory_tags (
|
|
133
|
+
memory_id TEXT NOT NULL REFERENCES memories(id) ON DELETE CASCADE,
|
|
134
|
+
tag TEXT NOT NULL,
|
|
135
|
+
PRIMARY KEY (memory_id, tag)
|
|
136
|
+
);
|
|
137
|
+
|
|
138
|
+
CREATE TABLE IF NOT EXISTS sessions (
|
|
139
|
+
id TEXT PRIMARY KEY,
|
|
140
|
+
agent_id TEXT REFERENCES agents(id) ON DELETE SET NULL,
|
|
141
|
+
project_id TEXT REFERENCES projects(id) ON DELETE SET NULL,
|
|
142
|
+
started_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
143
|
+
last_activity TEXT NOT NULL DEFAULT (datetime('now')),
|
|
144
|
+
metadata TEXT DEFAULT '{}'
|
|
145
|
+
);
|
|
146
|
+
|
|
147
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_memories_unique_key
|
|
148
|
+
ON memories(key, scope, COALESCE(agent_id, ''), COALESCE(project_id, ''), COALESCE(session_id, ''));
|
|
149
|
+
|
|
150
|
+
CREATE INDEX IF NOT EXISTS idx_memories_key ON memories(key);
|
|
151
|
+
CREATE INDEX IF NOT EXISTS idx_memories_scope ON memories(scope);
|
|
152
|
+
CREATE INDEX IF NOT EXISTS idx_memories_category ON memories(category);
|
|
153
|
+
CREATE INDEX IF NOT EXISTS idx_memories_status ON memories(status);
|
|
154
|
+
CREATE INDEX IF NOT EXISTS idx_memories_importance ON memories(importance);
|
|
155
|
+
CREATE INDEX IF NOT EXISTS idx_memories_agent ON memories(agent_id);
|
|
156
|
+
CREATE INDEX IF NOT EXISTS idx_memories_project ON memories(project_id);
|
|
157
|
+
CREATE INDEX IF NOT EXISTS idx_memories_session ON memories(session_id);
|
|
158
|
+
CREATE INDEX IF NOT EXISTS idx_memories_pinned ON memories(pinned);
|
|
159
|
+
CREATE INDEX IF NOT EXISTS idx_memories_expires ON memories(expires_at);
|
|
160
|
+
CREATE INDEX IF NOT EXISTS idx_memories_created ON memories(created_at);
|
|
161
|
+
CREATE INDEX IF NOT EXISTS idx_memory_tags_tag ON memory_tags(tag);
|
|
162
|
+
CREATE INDEX IF NOT EXISTS idx_memory_tags_memory ON memory_tags(memory_id);
|
|
163
|
+
CREATE INDEX IF NOT EXISTS idx_agents_name ON agents(name);
|
|
164
|
+
CREATE INDEX IF NOT EXISTS idx_sessions_agent ON sessions(agent_id);
|
|
165
|
+
CREATE INDEX IF NOT EXISTS idx_sessions_project ON sessions(project_id);
|
|
166
|
+
|
|
167
|
+
CREATE TABLE IF NOT EXISTS _migrations (
|
|
168
|
+
id INTEGER PRIMARY KEY,
|
|
169
|
+
applied_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
170
|
+
);
|
|
171
|
+
|
|
172
|
+
INSERT OR IGNORE INTO _migrations (id) VALUES (1);
|
|
173
|
+
`
|
|
174
|
+
];
|
|
175
|
+
var _db = null;
|
|
176
|
+
function getDatabase(dbPath) {
|
|
177
|
+
if (_db)
|
|
178
|
+
return _db;
|
|
179
|
+
const path = dbPath || getDbPath();
|
|
180
|
+
ensureDir(path);
|
|
181
|
+
_db = new Database(path, { create: true });
|
|
182
|
+
_db.run("PRAGMA journal_mode = WAL");
|
|
183
|
+
_db.run("PRAGMA busy_timeout = 5000");
|
|
184
|
+
_db.run("PRAGMA foreign_keys = ON");
|
|
185
|
+
runMigrations(_db);
|
|
186
|
+
return _db;
|
|
187
|
+
}
|
|
188
|
+
function runMigrations(db) {
|
|
189
|
+
try {
|
|
190
|
+
const result = db.query("SELECT MAX(id) as max_id FROM _migrations").get();
|
|
191
|
+
const currentLevel = result?.max_id ?? 0;
|
|
192
|
+
for (let i = currentLevel;i < MIGRATIONS.length; i++) {
|
|
193
|
+
try {
|
|
194
|
+
db.exec(MIGRATIONS[i]);
|
|
195
|
+
} catch {}
|
|
196
|
+
}
|
|
197
|
+
} catch {
|
|
198
|
+
for (const migration of MIGRATIONS) {
|
|
199
|
+
try {
|
|
200
|
+
db.exec(migration);
|
|
201
|
+
} catch {}
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
function now() {
|
|
206
|
+
return new Date().toISOString();
|
|
207
|
+
}
|
|
208
|
+
function uuid() {
|
|
209
|
+
return crypto.randomUUID();
|
|
210
|
+
}
|
|
211
|
+
function shortUuid() {
|
|
212
|
+
return crypto.randomUUID().slice(0, 8);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// src/db/memories.ts
|
|
216
|
+
function parseMemoryRow(row) {
|
|
217
|
+
return {
|
|
218
|
+
id: row["id"],
|
|
219
|
+
key: row["key"],
|
|
220
|
+
value: row["value"],
|
|
221
|
+
category: row["category"],
|
|
222
|
+
scope: row["scope"],
|
|
223
|
+
summary: row["summary"] || null,
|
|
224
|
+
tags: JSON.parse(row["tags"] || "[]"),
|
|
225
|
+
importance: row["importance"],
|
|
226
|
+
source: row["source"],
|
|
227
|
+
status: row["status"],
|
|
228
|
+
pinned: !!row["pinned"],
|
|
229
|
+
agent_id: row["agent_id"] || null,
|
|
230
|
+
project_id: row["project_id"] || null,
|
|
231
|
+
session_id: row["session_id"] || null,
|
|
232
|
+
metadata: JSON.parse(row["metadata"] || "{}"),
|
|
233
|
+
access_count: row["access_count"],
|
|
234
|
+
version: row["version"],
|
|
235
|
+
expires_at: row["expires_at"] || null,
|
|
236
|
+
created_at: row["created_at"],
|
|
237
|
+
updated_at: row["updated_at"],
|
|
238
|
+
accessed_at: row["accessed_at"] || null
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
function createMemory(input, dedupeMode = "merge", db) {
|
|
242
|
+
const d = db || getDatabase();
|
|
243
|
+
const timestamp = now();
|
|
244
|
+
let expiresAt = input.expires_at || null;
|
|
245
|
+
if (input.ttl_ms && !expiresAt) {
|
|
246
|
+
expiresAt = new Date(Date.now() + input.ttl_ms).toISOString();
|
|
247
|
+
}
|
|
248
|
+
const id = uuid();
|
|
249
|
+
const tags = input.tags || [];
|
|
250
|
+
const tagsJson = JSON.stringify(tags);
|
|
251
|
+
const metadataJson = JSON.stringify(input.metadata || {});
|
|
252
|
+
if (dedupeMode === "merge") {
|
|
253
|
+
const existing = d.query(`SELECT id, version FROM memories
|
|
254
|
+
WHERE key = ? AND scope = ?
|
|
255
|
+
AND COALESCE(agent_id, '') = ?
|
|
256
|
+
AND COALESCE(project_id, '') = ?
|
|
257
|
+
AND COALESCE(session_id, '') = ?`).get(input.key, input.scope || "private", input.agent_id || "", input.project_id || "", input.session_id || "");
|
|
258
|
+
if (existing) {
|
|
259
|
+
d.run(`UPDATE memories SET
|
|
260
|
+
value = ?, category = ?, summary = ?, tags = ?,
|
|
261
|
+
importance = ?, metadata = ?, expires_at = ?,
|
|
262
|
+
pinned = COALESCE(pinned, 0),
|
|
263
|
+
version = version + 1, updated_at = ?
|
|
264
|
+
WHERE id = ?`, [
|
|
265
|
+
input.value,
|
|
266
|
+
input.category || "knowledge",
|
|
267
|
+
input.summary || null,
|
|
268
|
+
tagsJson,
|
|
269
|
+
input.importance ?? 5,
|
|
270
|
+
metadataJson,
|
|
271
|
+
expiresAt,
|
|
272
|
+
timestamp,
|
|
273
|
+
existing.id
|
|
274
|
+
]);
|
|
275
|
+
d.run("DELETE FROM memory_tags WHERE memory_id = ?", [existing.id]);
|
|
276
|
+
const insertTag2 = d.prepare("INSERT OR IGNORE INTO memory_tags (memory_id, tag) VALUES (?, ?)");
|
|
277
|
+
for (const tag of tags) {
|
|
278
|
+
insertTag2.run(existing.id, tag);
|
|
279
|
+
}
|
|
280
|
+
return getMemory(existing.id, d);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
d.run(`INSERT INTO memories (id, key, value, category, scope, summary, tags, importance, source, status, pinned, agent_id, project_id, session_id, metadata, access_count, version, expires_at, created_at, updated_at)
|
|
284
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'active', 0, ?, ?, ?, ?, 0, 1, ?, ?, ?)`, [
|
|
285
|
+
id,
|
|
286
|
+
input.key,
|
|
287
|
+
input.value,
|
|
288
|
+
input.category || "knowledge",
|
|
289
|
+
input.scope || "private",
|
|
290
|
+
input.summary || null,
|
|
291
|
+
tagsJson,
|
|
292
|
+
input.importance ?? 5,
|
|
293
|
+
input.source || "agent",
|
|
294
|
+
input.agent_id || null,
|
|
295
|
+
input.project_id || null,
|
|
296
|
+
input.session_id || null,
|
|
297
|
+
metadataJson,
|
|
298
|
+
expiresAt,
|
|
299
|
+
timestamp,
|
|
300
|
+
timestamp
|
|
301
|
+
]);
|
|
302
|
+
const insertTag = d.prepare("INSERT OR IGNORE INTO memory_tags (memory_id, tag) VALUES (?, ?)");
|
|
303
|
+
for (const tag of tags) {
|
|
304
|
+
insertTag.run(id, tag);
|
|
305
|
+
}
|
|
306
|
+
return getMemory(id, d);
|
|
307
|
+
}
|
|
308
|
+
function getMemory(id, db) {
|
|
309
|
+
const d = db || getDatabase();
|
|
310
|
+
const row = d.query("SELECT * FROM memories WHERE id = ?").get(id);
|
|
311
|
+
if (!row)
|
|
312
|
+
return null;
|
|
313
|
+
return parseMemoryRow(row);
|
|
314
|
+
}
|
|
315
|
+
function listMemories(filter, db) {
|
|
316
|
+
const d = db || getDatabase();
|
|
317
|
+
const conditions = [];
|
|
318
|
+
const params = [];
|
|
319
|
+
if (filter) {
|
|
320
|
+
if (filter.scope) {
|
|
321
|
+
if (Array.isArray(filter.scope)) {
|
|
322
|
+
conditions.push(`scope IN (${filter.scope.map(() => "?").join(",")})`);
|
|
323
|
+
params.push(...filter.scope);
|
|
324
|
+
} else {
|
|
325
|
+
conditions.push("scope = ?");
|
|
326
|
+
params.push(filter.scope);
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
if (filter.category) {
|
|
330
|
+
if (Array.isArray(filter.category)) {
|
|
331
|
+
conditions.push(`category IN (${filter.category.map(() => "?").join(",")})`);
|
|
332
|
+
params.push(...filter.category);
|
|
333
|
+
} else {
|
|
334
|
+
conditions.push("category = ?");
|
|
335
|
+
params.push(filter.category);
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
if (filter.source) {
|
|
339
|
+
if (Array.isArray(filter.source)) {
|
|
340
|
+
conditions.push(`source IN (${filter.source.map(() => "?").join(",")})`);
|
|
341
|
+
params.push(...filter.source);
|
|
342
|
+
} else {
|
|
343
|
+
conditions.push("source = ?");
|
|
344
|
+
params.push(filter.source);
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
if (filter.status) {
|
|
348
|
+
if (Array.isArray(filter.status)) {
|
|
349
|
+
conditions.push(`status IN (${filter.status.map(() => "?").join(",")})`);
|
|
350
|
+
params.push(...filter.status);
|
|
351
|
+
} else {
|
|
352
|
+
conditions.push("status = ?");
|
|
353
|
+
params.push(filter.status);
|
|
354
|
+
}
|
|
355
|
+
} else {
|
|
356
|
+
conditions.push("status = 'active'");
|
|
357
|
+
}
|
|
358
|
+
if (filter.project_id) {
|
|
359
|
+
conditions.push("project_id = ?");
|
|
360
|
+
params.push(filter.project_id);
|
|
361
|
+
}
|
|
362
|
+
if (filter.agent_id) {
|
|
363
|
+
conditions.push("agent_id = ?");
|
|
364
|
+
params.push(filter.agent_id);
|
|
365
|
+
}
|
|
366
|
+
if (filter.session_id) {
|
|
367
|
+
conditions.push("session_id = ?");
|
|
368
|
+
params.push(filter.session_id);
|
|
369
|
+
}
|
|
370
|
+
if (filter.min_importance) {
|
|
371
|
+
conditions.push("importance >= ?");
|
|
372
|
+
params.push(filter.min_importance);
|
|
373
|
+
}
|
|
374
|
+
if (filter.pinned !== undefined) {
|
|
375
|
+
conditions.push("pinned = ?");
|
|
376
|
+
params.push(filter.pinned ? 1 : 0);
|
|
377
|
+
}
|
|
378
|
+
if (filter.tags && filter.tags.length > 0) {
|
|
379
|
+
for (const tag of filter.tags) {
|
|
380
|
+
conditions.push("id IN (SELECT memory_id FROM memory_tags WHERE tag = ?)");
|
|
381
|
+
params.push(tag);
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
if (filter.search) {
|
|
385
|
+
conditions.push("(key LIKE ? OR value LIKE ? OR summary LIKE ?)");
|
|
386
|
+
const term = `%${filter.search}%`;
|
|
387
|
+
params.push(term, term, term);
|
|
388
|
+
}
|
|
389
|
+
} else {
|
|
390
|
+
conditions.push("status = 'active'");
|
|
391
|
+
}
|
|
392
|
+
let sql = "SELECT * FROM memories";
|
|
393
|
+
if (conditions.length > 0) {
|
|
394
|
+
sql += ` WHERE ${conditions.join(" AND ")}`;
|
|
395
|
+
}
|
|
396
|
+
sql += " ORDER BY importance DESC, created_at DESC";
|
|
397
|
+
if (filter?.limit) {
|
|
398
|
+
sql += " LIMIT ?";
|
|
399
|
+
params.push(filter.limit);
|
|
400
|
+
}
|
|
401
|
+
if (filter?.offset) {
|
|
402
|
+
sql += " OFFSET ?";
|
|
403
|
+
params.push(filter.offset);
|
|
404
|
+
}
|
|
405
|
+
const rows = d.query(sql).all(...params);
|
|
406
|
+
return rows.map(parseMemoryRow);
|
|
407
|
+
}
|
|
408
|
+
function updateMemory(id, input, db) {
|
|
409
|
+
const d = db || getDatabase();
|
|
410
|
+
const existing = getMemory(id, d);
|
|
411
|
+
if (!existing)
|
|
412
|
+
throw new MemoryNotFoundError(id);
|
|
413
|
+
if (existing.version !== input.version) {
|
|
414
|
+
throw new VersionConflictError(id, input.version, existing.version);
|
|
415
|
+
}
|
|
416
|
+
const sets = ["version = version + 1", "updated_at = ?"];
|
|
417
|
+
const params = [now()];
|
|
418
|
+
if (input.value !== undefined) {
|
|
419
|
+
sets.push("value = ?");
|
|
420
|
+
params.push(input.value);
|
|
421
|
+
}
|
|
422
|
+
if (input.category !== undefined) {
|
|
423
|
+
sets.push("category = ?");
|
|
424
|
+
params.push(input.category);
|
|
425
|
+
}
|
|
426
|
+
if (input.scope !== undefined) {
|
|
427
|
+
sets.push("scope = ?");
|
|
428
|
+
params.push(input.scope);
|
|
429
|
+
}
|
|
430
|
+
if (input.summary !== undefined) {
|
|
431
|
+
sets.push("summary = ?");
|
|
432
|
+
params.push(input.summary);
|
|
433
|
+
}
|
|
434
|
+
if (input.importance !== undefined) {
|
|
435
|
+
sets.push("importance = ?");
|
|
436
|
+
params.push(input.importance);
|
|
437
|
+
}
|
|
438
|
+
if (input.pinned !== undefined) {
|
|
439
|
+
sets.push("pinned = ?");
|
|
440
|
+
params.push(input.pinned ? 1 : 0);
|
|
441
|
+
}
|
|
442
|
+
if (input.status !== undefined) {
|
|
443
|
+
sets.push("status = ?");
|
|
444
|
+
params.push(input.status);
|
|
445
|
+
}
|
|
446
|
+
if (input.metadata !== undefined) {
|
|
447
|
+
sets.push("metadata = ?");
|
|
448
|
+
params.push(JSON.stringify(input.metadata));
|
|
449
|
+
}
|
|
450
|
+
if (input.expires_at !== undefined) {
|
|
451
|
+
sets.push("expires_at = ?");
|
|
452
|
+
params.push(input.expires_at);
|
|
453
|
+
}
|
|
454
|
+
if (input.tags !== undefined) {
|
|
455
|
+
sets.push("tags = ?");
|
|
456
|
+
params.push(JSON.stringify(input.tags));
|
|
457
|
+
d.run("DELETE FROM memory_tags WHERE memory_id = ?", [id]);
|
|
458
|
+
const insertTag = d.prepare("INSERT OR IGNORE INTO memory_tags (memory_id, tag) VALUES (?, ?)");
|
|
459
|
+
for (const tag of input.tags) {
|
|
460
|
+
insertTag.run(id, tag);
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
params.push(id);
|
|
464
|
+
d.run(`UPDATE memories SET ${sets.join(", ")} WHERE id = ?`, params);
|
|
465
|
+
return getMemory(id, d);
|
|
466
|
+
}
|
|
467
|
+
function deleteMemory(id, db) {
|
|
468
|
+
const d = db || getDatabase();
|
|
469
|
+
const result = d.run("DELETE FROM memories WHERE id = ?", [id]);
|
|
470
|
+
return result.changes > 0;
|
|
471
|
+
}
|
|
472
|
+
function touchMemory(id, db) {
|
|
473
|
+
const d = db || getDatabase();
|
|
474
|
+
d.run("UPDATE memories SET access_count = access_count + 1, accessed_at = ? WHERE id = ?", [now(), id]);
|
|
475
|
+
}
|
|
476
|
+
function cleanExpiredMemories(db) {
|
|
477
|
+
const d = db || getDatabase();
|
|
478
|
+
const timestamp = now();
|
|
479
|
+
const result = d.run("DELETE FROM memories WHERE expires_at IS NOT NULL AND expires_at < ?", [timestamp]);
|
|
480
|
+
return result.changes;
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
// src/db/agents.ts
|
|
484
|
+
function parseAgentRow(row) {
|
|
485
|
+
return {
|
|
486
|
+
id: row["id"],
|
|
487
|
+
name: row["name"],
|
|
488
|
+
description: row["description"] || null,
|
|
489
|
+
role: row["role"] || null,
|
|
490
|
+
metadata: JSON.parse(row["metadata"] || "{}"),
|
|
491
|
+
created_at: row["created_at"],
|
|
492
|
+
last_seen_at: row["last_seen_at"]
|
|
493
|
+
};
|
|
494
|
+
}
|
|
495
|
+
function registerAgent(name, description, role, db) {
|
|
496
|
+
const d = db || getDatabase();
|
|
497
|
+
const timestamp = now();
|
|
498
|
+
const existing = d.query("SELECT * FROM agents WHERE name = ?").get(name);
|
|
499
|
+
if (existing) {
|
|
500
|
+
const existingId = existing["id"];
|
|
501
|
+
d.run("UPDATE agents SET last_seen_at = ? WHERE id = ?", [
|
|
502
|
+
timestamp,
|
|
503
|
+
existingId
|
|
504
|
+
]);
|
|
505
|
+
if (description) {
|
|
506
|
+
d.run("UPDATE agents SET description = ? WHERE id = ?", [
|
|
507
|
+
description,
|
|
508
|
+
existingId
|
|
509
|
+
]);
|
|
510
|
+
}
|
|
511
|
+
if (role) {
|
|
512
|
+
d.run("UPDATE agents SET role = ? WHERE id = ?", [
|
|
513
|
+
role,
|
|
514
|
+
existingId
|
|
515
|
+
]);
|
|
516
|
+
}
|
|
517
|
+
return getAgent(existingId, d);
|
|
518
|
+
}
|
|
519
|
+
const id = shortUuid();
|
|
520
|
+
d.run("INSERT INTO agents (id, name, description, role, created_at, last_seen_at) VALUES (?, ?, ?, ?, ?, ?)", [id, name, description || null, role || "agent", timestamp, timestamp]);
|
|
521
|
+
return getAgent(id, d);
|
|
522
|
+
}
|
|
523
|
+
function getAgent(idOrName, db) {
|
|
524
|
+
const d = db || getDatabase();
|
|
525
|
+
let row = d.query("SELECT * FROM agents WHERE id = ?").get(idOrName);
|
|
526
|
+
if (row)
|
|
527
|
+
return parseAgentRow(row);
|
|
528
|
+
row = d.query("SELECT * FROM agents WHERE name = ?").get(idOrName);
|
|
529
|
+
if (row)
|
|
530
|
+
return parseAgentRow(row);
|
|
531
|
+
const rows = d.query("SELECT * FROM agents WHERE id LIKE ?").all(`${idOrName}%`);
|
|
532
|
+
if (rows.length === 1)
|
|
533
|
+
return parseAgentRow(rows[0]);
|
|
534
|
+
return null;
|
|
535
|
+
}
|
|
536
|
+
function listAgents(db) {
|
|
537
|
+
const d = db || getDatabase();
|
|
538
|
+
const rows = d.query("SELECT * FROM agents ORDER BY last_seen_at DESC").all();
|
|
539
|
+
return rows.map(parseAgentRow);
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
// src/db/projects.ts
|
|
543
|
+
function parseProjectRow(row) {
|
|
544
|
+
return {
|
|
545
|
+
id: row["id"],
|
|
546
|
+
name: row["name"],
|
|
547
|
+
path: row["path"],
|
|
548
|
+
description: row["description"] || null,
|
|
549
|
+
memory_prefix: row["memory_prefix"] || null,
|
|
550
|
+
created_at: row["created_at"],
|
|
551
|
+
updated_at: row["updated_at"]
|
|
552
|
+
};
|
|
553
|
+
}
|
|
554
|
+
function registerProject(name, path, description, memoryPrefix, db) {
|
|
555
|
+
const d = db || getDatabase();
|
|
556
|
+
const timestamp = now();
|
|
557
|
+
const existing = d.query("SELECT * FROM projects WHERE path = ?").get(path);
|
|
558
|
+
if (existing) {
|
|
559
|
+
const existingId = existing["id"];
|
|
560
|
+
d.run("UPDATE projects SET updated_at = ? WHERE id = ?", [
|
|
561
|
+
timestamp,
|
|
562
|
+
existingId
|
|
563
|
+
]);
|
|
564
|
+
return parseProjectRow(existing);
|
|
565
|
+
}
|
|
566
|
+
const id = uuid();
|
|
567
|
+
d.run("INSERT INTO projects (id, name, path, description, memory_prefix, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)", [id, name, path, description || null, memoryPrefix || null, timestamp, timestamp]);
|
|
568
|
+
return getProject(id, d);
|
|
569
|
+
}
|
|
570
|
+
function getProject(idOrPath, db) {
|
|
571
|
+
const d = db || getDatabase();
|
|
572
|
+
let row = d.query("SELECT * FROM projects WHERE id = ?").get(idOrPath);
|
|
573
|
+
if (row)
|
|
574
|
+
return parseProjectRow(row);
|
|
575
|
+
row = d.query("SELECT * FROM projects WHERE path = ?").get(idOrPath);
|
|
576
|
+
if (row)
|
|
577
|
+
return parseProjectRow(row);
|
|
578
|
+
return null;
|
|
579
|
+
}
|
|
580
|
+
function listProjects(db) {
|
|
581
|
+
const d = db || getDatabase();
|
|
582
|
+
const rows = d.query("SELECT * FROM projects ORDER BY updated_at DESC").all();
|
|
583
|
+
return rows.map(parseProjectRow);
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
// src/lib/search.ts
|
|
587
|
+
function parseMemoryRow2(row) {
|
|
588
|
+
return {
|
|
589
|
+
id: row["id"],
|
|
590
|
+
key: row["key"],
|
|
591
|
+
value: row["value"],
|
|
592
|
+
category: row["category"],
|
|
593
|
+
scope: row["scope"],
|
|
594
|
+
summary: row["summary"] || null,
|
|
595
|
+
tags: JSON.parse(row["tags"] || "[]"),
|
|
596
|
+
importance: row["importance"],
|
|
597
|
+
source: row["source"],
|
|
598
|
+
status: row["status"],
|
|
599
|
+
pinned: !!row["pinned"],
|
|
600
|
+
agent_id: row["agent_id"] || null,
|
|
601
|
+
project_id: row["project_id"] || null,
|
|
602
|
+
session_id: row["session_id"] || null,
|
|
603
|
+
metadata: JSON.parse(row["metadata"] || "{}"),
|
|
604
|
+
access_count: row["access_count"],
|
|
605
|
+
version: row["version"],
|
|
606
|
+
expires_at: row["expires_at"] || null,
|
|
607
|
+
created_at: row["created_at"],
|
|
608
|
+
updated_at: row["updated_at"],
|
|
609
|
+
accessed_at: row["accessed_at"] || null
|
|
610
|
+
};
|
|
611
|
+
}
|
|
612
|
+
function determineMatchType(memory, queryLower) {
|
|
613
|
+
if (memory.key.toLowerCase() === queryLower)
|
|
614
|
+
return "exact";
|
|
615
|
+
if (memory.tags.some((t) => t.toLowerCase() === queryLower))
|
|
616
|
+
return "tag";
|
|
617
|
+
return "fuzzy";
|
|
618
|
+
}
|
|
619
|
+
function computeScore(memory, queryLower) {
|
|
620
|
+
let score = 0;
|
|
621
|
+
const keyLower = memory.key.toLowerCase();
|
|
622
|
+
if (keyLower === queryLower) {
|
|
623
|
+
score += 10;
|
|
624
|
+
} else if (keyLower.includes(queryLower)) {
|
|
625
|
+
score += 7;
|
|
626
|
+
}
|
|
627
|
+
if (memory.tags.some((t) => t.toLowerCase() === queryLower)) {
|
|
628
|
+
score += 6;
|
|
629
|
+
}
|
|
630
|
+
if (memory.summary && memory.summary.toLowerCase().includes(queryLower)) {
|
|
631
|
+
score += 4;
|
|
632
|
+
}
|
|
633
|
+
if (memory.value.toLowerCase().includes(queryLower)) {
|
|
634
|
+
score += 3;
|
|
635
|
+
}
|
|
636
|
+
return score;
|
|
637
|
+
}
|
|
638
|
+
function searchMemories(query, filter, db) {
|
|
639
|
+
const d = db || getDatabase();
|
|
640
|
+
const queryLower = query.toLowerCase();
|
|
641
|
+
const queryParam = `%${query}%`;
|
|
642
|
+
const conditions = [];
|
|
643
|
+
const params = [];
|
|
644
|
+
conditions.push("m.status = 'active'");
|
|
645
|
+
conditions.push("(m.expires_at IS NULL OR m.expires_at >= datetime('now'))");
|
|
646
|
+
conditions.push(`(m.key LIKE ? OR m.value LIKE ? OR m.summary LIKE ? OR m.id IN (SELECT memory_id FROM memory_tags WHERE tag LIKE ?))`);
|
|
647
|
+
params.push(queryParam, queryParam, queryParam, queryParam);
|
|
648
|
+
if (filter) {
|
|
649
|
+
if (filter.scope) {
|
|
650
|
+
if (Array.isArray(filter.scope)) {
|
|
651
|
+
conditions.push(`m.scope IN (${filter.scope.map(() => "?").join(",")})`);
|
|
652
|
+
params.push(...filter.scope);
|
|
653
|
+
} else {
|
|
654
|
+
conditions.push("m.scope = ?");
|
|
655
|
+
params.push(filter.scope);
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
if (filter.category) {
|
|
659
|
+
if (Array.isArray(filter.category)) {
|
|
660
|
+
conditions.push(`m.category IN (${filter.category.map(() => "?").join(",")})`);
|
|
661
|
+
params.push(...filter.category);
|
|
662
|
+
} else {
|
|
663
|
+
conditions.push("m.category = ?");
|
|
664
|
+
params.push(filter.category);
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
if (filter.source) {
|
|
668
|
+
if (Array.isArray(filter.source)) {
|
|
669
|
+
conditions.push(`m.source IN (${filter.source.map(() => "?").join(",")})`);
|
|
670
|
+
params.push(...filter.source);
|
|
671
|
+
} else {
|
|
672
|
+
conditions.push("m.source = ?");
|
|
673
|
+
params.push(filter.source);
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
if (filter.status) {
|
|
677
|
+
conditions.shift();
|
|
678
|
+
if (Array.isArray(filter.status)) {
|
|
679
|
+
conditions.push(`m.status IN (${filter.status.map(() => "?").join(",")})`);
|
|
680
|
+
params.push(...filter.status);
|
|
681
|
+
} else {
|
|
682
|
+
conditions.push("m.status = ?");
|
|
683
|
+
params.push(filter.status);
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
if (filter.project_id) {
|
|
687
|
+
conditions.push("m.project_id = ?");
|
|
688
|
+
params.push(filter.project_id);
|
|
689
|
+
}
|
|
690
|
+
if (filter.agent_id) {
|
|
691
|
+
conditions.push("m.agent_id = ?");
|
|
692
|
+
params.push(filter.agent_id);
|
|
693
|
+
}
|
|
694
|
+
if (filter.session_id) {
|
|
695
|
+
conditions.push("m.session_id = ?");
|
|
696
|
+
params.push(filter.session_id);
|
|
697
|
+
}
|
|
698
|
+
if (filter.min_importance) {
|
|
699
|
+
conditions.push("m.importance >= ?");
|
|
700
|
+
params.push(filter.min_importance);
|
|
701
|
+
}
|
|
702
|
+
if (filter.pinned !== undefined) {
|
|
703
|
+
conditions.push("m.pinned = ?");
|
|
704
|
+
params.push(filter.pinned ? 1 : 0);
|
|
705
|
+
}
|
|
706
|
+
if (filter.tags && filter.tags.length > 0) {
|
|
707
|
+
for (const tag of filter.tags) {
|
|
708
|
+
conditions.push("m.id IN (SELECT memory_id FROM memory_tags WHERE tag = ?)");
|
|
709
|
+
params.push(tag);
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
const sql = `SELECT m.* FROM memories m WHERE ${conditions.join(" AND ")}`;
|
|
714
|
+
const rows = d.query(sql).all(...params);
|
|
715
|
+
const scored = [];
|
|
716
|
+
for (const row of rows) {
|
|
717
|
+
const memory = parseMemoryRow2(row);
|
|
718
|
+
const rawScore = computeScore(memory, queryLower);
|
|
719
|
+
if (rawScore === 0)
|
|
720
|
+
continue;
|
|
721
|
+
const weightedScore = rawScore * memory.importance / 10;
|
|
722
|
+
const matchType = determineMatchType(memory, queryLower);
|
|
723
|
+
scored.push({
|
|
724
|
+
memory,
|
|
725
|
+
score: weightedScore,
|
|
726
|
+
match_type: matchType
|
|
727
|
+
});
|
|
728
|
+
}
|
|
729
|
+
scored.sort((a, b) => {
|
|
730
|
+
if (b.score !== a.score)
|
|
731
|
+
return b.score - a.score;
|
|
732
|
+
return b.memory.importance - a.memory.importance;
|
|
733
|
+
});
|
|
734
|
+
const offset = filter?.offset ?? 0;
|
|
735
|
+
const limit = filter?.limit ?? scored.length;
|
|
736
|
+
return scored.slice(offset, offset + limit);
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
// src/server/index.ts
|
|
740
|
+
var DEFAULT_PORT = 19428;
|
|
741
|
+
function parsePort() {
|
|
742
|
+
const envPort = process.env["PORT"];
|
|
743
|
+
if (envPort) {
|
|
744
|
+
const p = parseInt(envPort, 10);
|
|
745
|
+
if (!Number.isNaN(p))
|
|
746
|
+
return p;
|
|
747
|
+
}
|
|
748
|
+
const portArg = process.argv.find((a) => a === "--port" || a.startsWith("--port="));
|
|
749
|
+
if (portArg) {
|
|
750
|
+
if (portArg.includes("=")) {
|
|
751
|
+
return parseInt(portArg.split("=")[1], 10) || DEFAULT_PORT;
|
|
752
|
+
}
|
|
753
|
+
const idx = process.argv.indexOf(portArg);
|
|
754
|
+
return parseInt(process.argv[idx + 1], 10) || DEFAULT_PORT;
|
|
755
|
+
}
|
|
756
|
+
return DEFAULT_PORT;
|
|
757
|
+
}
|
|
758
|
+
var CORS_HEADERS = {
|
|
759
|
+
"Access-Control-Allow-Origin": "*",
|
|
760
|
+
"Access-Control-Allow-Methods": "GET, POST, PATCH, DELETE, OPTIONS",
|
|
761
|
+
"Access-Control-Allow-Headers": "Content-Type, Authorization",
|
|
762
|
+
"Access-Control-Max-Age": "86400"
|
|
763
|
+
};
|
|
764
|
+
function json(data, status = 200) {
|
|
765
|
+
return new Response(JSON.stringify(data), {
|
|
766
|
+
status,
|
|
767
|
+
headers: { "Content-Type": "application/json", ...CORS_HEADERS }
|
|
768
|
+
});
|
|
769
|
+
}
|
|
770
|
+
function errorResponse(message, status, details) {
|
|
771
|
+
const body = { error: message };
|
|
772
|
+
if (details !== undefined)
|
|
773
|
+
body["details"] = details;
|
|
774
|
+
return json(body, status);
|
|
775
|
+
}
|
|
776
|
+
async function readJson(req) {
|
|
777
|
+
try {
|
|
778
|
+
return await req.json();
|
|
779
|
+
} catch {
|
|
780
|
+
return null;
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
function getSearchParams(url) {
|
|
784
|
+
const params = {};
|
|
785
|
+
url.searchParams.forEach((v, k) => {
|
|
786
|
+
params[k] = v;
|
|
787
|
+
});
|
|
788
|
+
return params;
|
|
789
|
+
}
|
|
790
|
+
var routes = [];
|
|
791
|
+
function addRoute(method, path, handler) {
|
|
792
|
+
const paramNames = [];
|
|
793
|
+
const patternStr = path.replace(/:(\w+)/g, (_match, name) => {
|
|
794
|
+
paramNames.push(name);
|
|
795
|
+
return "([^/]+)";
|
|
796
|
+
});
|
|
797
|
+
routes.push({
|
|
798
|
+
method,
|
|
799
|
+
pattern: new RegExp(`^${patternStr}$`),
|
|
800
|
+
paramNames,
|
|
801
|
+
handler
|
|
802
|
+
});
|
|
803
|
+
}
|
|
804
|
+
function matchRoute(method, pathname) {
|
|
805
|
+
for (const route of routes) {
|
|
806
|
+
if (route.method !== method)
|
|
807
|
+
continue;
|
|
808
|
+
const match = pathname.match(route.pattern);
|
|
809
|
+
if (match) {
|
|
810
|
+
const params = {};
|
|
811
|
+
route.paramNames.forEach((name, i) => {
|
|
812
|
+
params[name] = match[i + 1];
|
|
813
|
+
});
|
|
814
|
+
return { handler: route.handler, params };
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
return null;
|
|
818
|
+
}
|
|
819
|
+
addRoute("GET", "/api/memories", (_req, url) => {
|
|
820
|
+
const q = getSearchParams(url);
|
|
821
|
+
const filter = {};
|
|
822
|
+
if (q["scope"])
|
|
823
|
+
filter.scope = q["scope"];
|
|
824
|
+
if (q["category"])
|
|
825
|
+
filter.category = q["category"];
|
|
826
|
+
if (q["tags"])
|
|
827
|
+
filter.tags = q["tags"].split(",");
|
|
828
|
+
if (q["min_importance"])
|
|
829
|
+
filter.min_importance = parseInt(q["min_importance"], 10);
|
|
830
|
+
if (q["pinned"] !== undefined && q["pinned"] !== "")
|
|
831
|
+
filter.pinned = q["pinned"] === "true";
|
|
832
|
+
if (q["agent_id"])
|
|
833
|
+
filter.agent_id = q["agent_id"];
|
|
834
|
+
if (q["project_id"])
|
|
835
|
+
filter.project_id = q["project_id"];
|
|
836
|
+
if (q["limit"])
|
|
837
|
+
filter.limit = parseInt(q["limit"], 10);
|
|
838
|
+
if (q["offset"])
|
|
839
|
+
filter.offset = parseInt(q["offset"], 10);
|
|
840
|
+
const memories = listMemories(filter);
|
|
841
|
+
return json({ memories, count: memories.length });
|
|
842
|
+
});
|
|
843
|
+
addRoute("GET", "/api/memories/stats", (_req) => {
|
|
844
|
+
const db = getDatabase();
|
|
845
|
+
const total = db.query("SELECT COUNT(*) as c FROM memories WHERE status = 'active'").get().c;
|
|
846
|
+
const byScope = db.query("SELECT scope, COUNT(*) as c FROM memories WHERE status = 'active' GROUP BY scope").all();
|
|
847
|
+
const byCategory = db.query("SELECT category, COUNT(*) as c FROM memories WHERE status = 'active' GROUP BY category").all();
|
|
848
|
+
const byStatus = db.query("SELECT status, COUNT(*) as c FROM memories GROUP BY status").all();
|
|
849
|
+
const pinnedCount = db.query("SELECT COUNT(*) as c FROM memories WHERE pinned = 1 AND status = 'active'").get().c;
|
|
850
|
+
const expiredCount = db.query("SELECT COUNT(*) as c FROM memories WHERE status = 'expired' OR (expires_at IS NOT NULL AND expires_at < datetime('now'))").get().c;
|
|
851
|
+
const stats = {
|
|
852
|
+
total,
|
|
853
|
+
by_scope: { global: 0, shared: 0, private: 0 },
|
|
854
|
+
by_category: { preference: 0, fact: 0, knowledge: 0, history: 0 },
|
|
855
|
+
by_status: { active: 0, archived: 0, expired: 0 },
|
|
856
|
+
by_agent: {},
|
|
857
|
+
pinned_count: pinnedCount,
|
|
858
|
+
expired_count: expiredCount
|
|
859
|
+
};
|
|
860
|
+
for (const row of byScope)
|
|
861
|
+
stats.by_scope[row.scope] = row.c;
|
|
862
|
+
for (const row of byCategory)
|
|
863
|
+
stats.by_category[row.category] = row.c;
|
|
864
|
+
for (const row of byStatus) {
|
|
865
|
+
if (row.status in stats.by_status) {
|
|
866
|
+
stats.by_status[row.status] = row.c;
|
|
867
|
+
}
|
|
868
|
+
}
|
|
869
|
+
const byAgent = db.query("SELECT agent_id, COUNT(*) as c FROM memories WHERE status = 'active' AND agent_id IS NOT NULL GROUP BY agent_id").all();
|
|
870
|
+
for (const row of byAgent)
|
|
871
|
+
stats.by_agent[row.agent_id] = row.c;
|
|
872
|
+
return json(stats);
|
|
873
|
+
});
|
|
874
|
+
addRoute("POST", "/api/memories/search", async (req) => {
|
|
875
|
+
const body = await readJson(req);
|
|
876
|
+
if (!body || typeof body["query"] !== "string") {
|
|
877
|
+
return errorResponse("Missing required field: query", 400);
|
|
878
|
+
}
|
|
879
|
+
const filter = {};
|
|
880
|
+
if (body["scope"])
|
|
881
|
+
filter.scope = body["scope"];
|
|
882
|
+
if (body["category"])
|
|
883
|
+
filter.category = body["category"];
|
|
884
|
+
if (body["tags"])
|
|
885
|
+
filter.tags = body["tags"];
|
|
886
|
+
if (body["limit"])
|
|
887
|
+
filter.limit = body["limit"];
|
|
888
|
+
const results = searchMemories(body["query"], filter);
|
|
889
|
+
return json({ results, count: results.length });
|
|
890
|
+
});
|
|
891
|
+
addRoute("POST", "/api/memories/export", async (req) => {
|
|
892
|
+
const body = await readJson(req) || {};
|
|
893
|
+
const filter = {};
|
|
894
|
+
if (body["scope"])
|
|
895
|
+
filter.scope = body["scope"];
|
|
896
|
+
if (body["category"])
|
|
897
|
+
filter.category = body["category"];
|
|
898
|
+
if (body["agent_id"])
|
|
899
|
+
filter.agent_id = body["agent_id"];
|
|
900
|
+
if (body["project_id"])
|
|
901
|
+
filter.project_id = body["project_id"];
|
|
902
|
+
if (body["tags"])
|
|
903
|
+
filter.tags = body["tags"];
|
|
904
|
+
filter.limit = body["limit"] || 1e4;
|
|
905
|
+
const memories = listMemories(filter);
|
|
906
|
+
return json({ memories, count: memories.length });
|
|
907
|
+
});
|
|
908
|
+
addRoute("POST", "/api/memories/import", async (req) => {
|
|
909
|
+
const body = await readJson(req);
|
|
910
|
+
if (!body || !Array.isArray(body["memories"])) {
|
|
911
|
+
return errorResponse("Missing required field: memories (array)", 400);
|
|
912
|
+
}
|
|
913
|
+
const overwrite = body["overwrite"] !== false;
|
|
914
|
+
const dedupeMode = overwrite ? "merge" : "create";
|
|
915
|
+
const memoriesArr = body["memories"];
|
|
916
|
+
let imported = 0;
|
|
917
|
+
const errors = [];
|
|
918
|
+
for (const mem of memoriesArr) {
|
|
919
|
+
try {
|
|
920
|
+
createMemory({
|
|
921
|
+
...mem,
|
|
922
|
+
source: mem["source"] || "imported"
|
|
923
|
+
}, dedupeMode);
|
|
924
|
+
imported++;
|
|
925
|
+
} catch (e) {
|
|
926
|
+
errors.push(`Failed to import "${mem["key"]}": ${e instanceof Error ? e.message : String(e)}`);
|
|
927
|
+
}
|
|
928
|
+
}
|
|
929
|
+
return json({ imported, errors, total: memoriesArr.length }, 201);
|
|
930
|
+
});
|
|
931
|
+
addRoute("POST", "/api/memories/clean", () => {
|
|
932
|
+
const cleaned = cleanExpiredMemories();
|
|
933
|
+
return json({ cleaned });
|
|
934
|
+
});
|
|
935
|
+
addRoute("POST", "/api/memories", async (req) => {
|
|
936
|
+
const body = await readJson(req);
|
|
937
|
+
if (!body) {
|
|
938
|
+
return errorResponse("Invalid JSON body", 400);
|
|
939
|
+
}
|
|
940
|
+
if (!body["key"] || !body["value"]) {
|
|
941
|
+
return errorResponse("Missing required fields: key, value", 400);
|
|
942
|
+
}
|
|
943
|
+
try {
|
|
944
|
+
const memory = createMemory(body);
|
|
945
|
+
return json(memory, 201);
|
|
946
|
+
} catch (e) {
|
|
947
|
+
if (e instanceof DuplicateMemoryError) {
|
|
948
|
+
return errorResponse(e.message, 409);
|
|
949
|
+
}
|
|
950
|
+
throw e;
|
|
951
|
+
}
|
|
952
|
+
});
|
|
953
|
+
addRoute("GET", "/api/memories/:id", (_req, _url, params) => {
|
|
954
|
+
const memory = getMemory(params["id"]);
|
|
955
|
+
if (!memory) {
|
|
956
|
+
return errorResponse("Memory not found", 404);
|
|
957
|
+
}
|
|
958
|
+
touchMemory(memory.id);
|
|
959
|
+
return json(memory);
|
|
960
|
+
});
|
|
961
|
+
addRoute("PATCH", "/api/memories/:id", async (req, _url, params) => {
|
|
962
|
+
const body = await readJson(req);
|
|
963
|
+
if (!body) {
|
|
964
|
+
return errorResponse("Invalid JSON body", 400);
|
|
965
|
+
}
|
|
966
|
+
if (body["version"] === undefined) {
|
|
967
|
+
return errorResponse("Missing required field: version", 400);
|
|
968
|
+
}
|
|
969
|
+
try {
|
|
970
|
+
const memory = updateMemory(params["id"], body);
|
|
971
|
+
return json(memory);
|
|
972
|
+
} catch (e) {
|
|
973
|
+
if (e instanceof MemoryNotFoundError) {
|
|
974
|
+
return errorResponse(e.message, 404);
|
|
975
|
+
}
|
|
976
|
+
if (e instanceof VersionConflictError) {
|
|
977
|
+
return errorResponse(e.message, 409, {
|
|
978
|
+
expected: e.expected,
|
|
979
|
+
actual: e.actual
|
|
980
|
+
});
|
|
981
|
+
}
|
|
982
|
+
throw e;
|
|
983
|
+
}
|
|
984
|
+
});
|
|
985
|
+
addRoute("DELETE", "/api/memories/:id", (_req, _url, params) => {
|
|
986
|
+
const deleted = deleteMemory(params["id"]);
|
|
987
|
+
if (!deleted) {
|
|
988
|
+
return errorResponse("Memory not found", 404);
|
|
989
|
+
}
|
|
990
|
+
return json({ deleted: true });
|
|
991
|
+
});
|
|
992
|
+
addRoute("GET", "/api/agents", () => {
|
|
993
|
+
const agents = listAgents();
|
|
994
|
+
return json({ agents, count: agents.length });
|
|
995
|
+
});
|
|
996
|
+
addRoute("POST", "/api/agents", async (req) => {
|
|
997
|
+
const body = await readJson(req);
|
|
998
|
+
if (!body || !body["name"]) {
|
|
999
|
+
return errorResponse("Missing required field: name", 400);
|
|
1000
|
+
}
|
|
1001
|
+
const agent = registerAgent(body["name"], body["description"], body["role"]);
|
|
1002
|
+
return json(agent, 201);
|
|
1003
|
+
});
|
|
1004
|
+
addRoute("GET", "/api/agents/:id", (_req, _url, params) => {
|
|
1005
|
+
const agent = getAgent(params["id"]);
|
|
1006
|
+
if (!agent) {
|
|
1007
|
+
return errorResponse("Agent not found", 404);
|
|
1008
|
+
}
|
|
1009
|
+
return json(agent);
|
|
1010
|
+
});
|
|
1011
|
+
addRoute("GET", "/api/projects", () => {
|
|
1012
|
+
const projects = listProjects();
|
|
1013
|
+
return json({ projects, count: projects.length });
|
|
1014
|
+
});
|
|
1015
|
+
addRoute("POST", "/api/projects", async (req) => {
|
|
1016
|
+
const body = await readJson(req);
|
|
1017
|
+
if (!body || !body["name"] || !body["path"]) {
|
|
1018
|
+
return errorResponse("Missing required fields: name, path", 400);
|
|
1019
|
+
}
|
|
1020
|
+
const project = registerProject(body["name"], body["path"], body["description"], body["memory_prefix"]);
|
|
1021
|
+
return json(project, 201);
|
|
1022
|
+
});
|
|
1023
|
+
addRoute("GET", "/api/inject", (_req, url) => {
|
|
1024
|
+
const q = getSearchParams(url);
|
|
1025
|
+
const maxTokens = q["max_tokens"] ? parseInt(q["max_tokens"], 10) : 500;
|
|
1026
|
+
const minImportance = 3;
|
|
1027
|
+
const categories = [
|
|
1028
|
+
"preference",
|
|
1029
|
+
"fact",
|
|
1030
|
+
"knowledge"
|
|
1031
|
+
];
|
|
1032
|
+
const allMemories = [];
|
|
1033
|
+
const globalMems = listMemories({
|
|
1034
|
+
scope: "global",
|
|
1035
|
+
category: categories,
|
|
1036
|
+
min_importance: minImportance,
|
|
1037
|
+
status: "active",
|
|
1038
|
+
project_id: q["project_id"],
|
|
1039
|
+
limit: 50
|
|
1040
|
+
});
|
|
1041
|
+
allMemories.push(...globalMems);
|
|
1042
|
+
if (q["project_id"]) {
|
|
1043
|
+
const sharedMems = listMemories({
|
|
1044
|
+
scope: "shared",
|
|
1045
|
+
category: categories,
|
|
1046
|
+
min_importance: minImportance,
|
|
1047
|
+
status: "active",
|
|
1048
|
+
project_id: q["project_id"],
|
|
1049
|
+
limit: 50
|
|
1050
|
+
});
|
|
1051
|
+
allMemories.push(...sharedMems);
|
|
1052
|
+
}
|
|
1053
|
+
if (q["agent_id"]) {
|
|
1054
|
+
const privateMems = listMemories({
|
|
1055
|
+
scope: "private",
|
|
1056
|
+
category: categories,
|
|
1057
|
+
min_importance: minImportance,
|
|
1058
|
+
status: "active",
|
|
1059
|
+
agent_id: q["agent_id"],
|
|
1060
|
+
limit: 50
|
|
1061
|
+
});
|
|
1062
|
+
allMemories.push(...privateMems);
|
|
1063
|
+
}
|
|
1064
|
+
const seen = new Set;
|
|
1065
|
+
const unique = allMemories.filter((m) => {
|
|
1066
|
+
if (seen.has(m.id))
|
|
1067
|
+
return false;
|
|
1068
|
+
seen.add(m.id);
|
|
1069
|
+
return true;
|
|
1070
|
+
});
|
|
1071
|
+
unique.sort((a, b) => {
|
|
1072
|
+
if (b.importance !== a.importance)
|
|
1073
|
+
return b.importance - a.importance;
|
|
1074
|
+
return new Date(b.updated_at).getTime() - new Date(a.updated_at).getTime();
|
|
1075
|
+
});
|
|
1076
|
+
const charBudget = maxTokens * 4;
|
|
1077
|
+
const lines = [];
|
|
1078
|
+
let totalChars = 0;
|
|
1079
|
+
for (const m of unique) {
|
|
1080
|
+
const line = `- [${m.scope}/${m.category}] ${m.key}: ${m.value}`;
|
|
1081
|
+
if (totalChars + line.length > charBudget)
|
|
1082
|
+
break;
|
|
1083
|
+
lines.push(line);
|
|
1084
|
+
totalChars += line.length;
|
|
1085
|
+
touchMemory(m.id);
|
|
1086
|
+
}
|
|
1087
|
+
if (lines.length === 0) {
|
|
1088
|
+
return json({ context: "", memories_count: 0 });
|
|
1089
|
+
}
|
|
1090
|
+
const context = `<agent-memories>
|
|
1091
|
+
${lines.join(`
|
|
1092
|
+
`)}
|
|
1093
|
+
</agent-memories>`;
|
|
1094
|
+
return json({ context, memories_count: lines.length });
|
|
1095
|
+
});
|
|
1096
|
+
async function findFreePort(start) {
|
|
1097
|
+
for (let port = start;port < start + 100; port++) {
|
|
1098
|
+
try {
|
|
1099
|
+
const server = Bun.serve({ port, fetch: () => new Response("") });
|
|
1100
|
+
server.stop(true);
|
|
1101
|
+
return port;
|
|
1102
|
+
} catch {}
|
|
1103
|
+
}
|
|
1104
|
+
return start;
|
|
1105
|
+
}
|
|
1106
|
+
function startServer(port) {
|
|
1107
|
+
Bun.serve({
|
|
1108
|
+
port,
|
|
1109
|
+
async fetch(req) {
|
|
1110
|
+
const url = new URL(req.url);
|
|
1111
|
+
const { pathname } = url;
|
|
1112
|
+
if (req.method === "OPTIONS") {
|
|
1113
|
+
return new Response(null, { status: 204, headers: CORS_HEADERS });
|
|
1114
|
+
}
|
|
1115
|
+
if (pathname === "/api/health" || pathname === "/health") {
|
|
1116
|
+
return json({ status: "ok", version: "0.1.0" });
|
|
1117
|
+
}
|
|
1118
|
+
const matched = matchRoute(req.method, pathname);
|
|
1119
|
+
if (!matched) {
|
|
1120
|
+
return errorResponse("Not found", 404);
|
|
1121
|
+
}
|
|
1122
|
+
try {
|
|
1123
|
+
return await matched.handler(req, url, matched.params);
|
|
1124
|
+
} catch (e) {
|
|
1125
|
+
console.error(`[mementos-serve] ${req.method} ${pathname}:`, e);
|
|
1126
|
+
const message = e instanceof Error ? e.message : "Internal server error";
|
|
1127
|
+
return errorResponse(message, 500);
|
|
1128
|
+
}
|
|
1129
|
+
}
|
|
1130
|
+
});
|
|
1131
|
+
console.log(`Mementos server listening on http://localhost:${port}`);
|
|
1132
|
+
}
|
|
1133
|
+
async function main() {
|
|
1134
|
+
const requestedPort = parsePort();
|
|
1135
|
+
const port = await findFreePort(requestedPort);
|
|
1136
|
+
if (port !== requestedPort) {
|
|
1137
|
+
console.log(`Port ${requestedPort} in use, using ${port}`);
|
|
1138
|
+
}
|
|
1139
|
+
startServer(port);
|
|
1140
|
+
}
|
|
1141
|
+
main();
|
|
1142
|
+
export {
|
|
1143
|
+
startServer
|
|
1144
|
+
};
|