agent-lyra 0.6.5 → 0.7.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 +42 -1
- package/bin/agent-lyra.js +3 -1
- package/package.json +1 -1
- package/src/app-builder/init.js +21 -1
- package/src/app-builder/preview.js +9 -0
- package/src/framework/agent.js +173 -0
- package/src/framework/run.py +111 -0
- package/src/intelligence/graphsnip-provider.d.ts +5 -0
- package/src/intelligence/graphsnip-provider.js +57 -0
- package/src/memory/LICENSE +21 -0
- package/src/memory/README.md +5 -0
- package/src/memory/UPSTREAM.json +14 -0
- package/src/memory/bridge-cli.js +16 -0
- package/src/memory/bridge.js +18 -0
- package/src/memory/cloud-sync-actions.js +61 -0
- package/src/memory/contract.json +19 -2
- package/src/memory/index.js +3 -255
- package/src/memory/local-store.js +209 -0
- package/src/memory/package.json +33 -0
- package/src/memory/proposals.js +6 -0
- package/src/memory/standalone.d.ts +50 -0
- package/src/memory/standalone.js +1 -0
- package/src/runtime/run-agent.js +16 -6
- package/src/studio/browser.js +19 -5
- package/src/studio/export.js +5 -1
- package/src/studio/project.js +27 -2
- package/src/studio/server.js +8 -1
package/src/memory/contract.json
CHANGED
|
@@ -20,8 +20,25 @@
|
|
|
20
20
|
"evidence": 16,
|
|
21
21
|
"id": 128
|
|
22
22
|
},
|
|
23
|
-
"adapters": {
|
|
24
|
-
|
|
23
|
+
"adapters": {
|
|
24
|
+
"coding": {
|
|
25
|
+
"types": [
|
|
26
|
+
"corrective"
|
|
27
|
+
],
|
|
28
|
+
"prefix": "test:",
|
|
29
|
+
"check": "test",
|
|
30
|
+
"error": "Verification requires a linked passing coding test, a compatibility context, and explicit review."
|
|
31
|
+
},
|
|
32
|
+
"practice": {
|
|
33
|
+
"types": [
|
|
34
|
+
"corrective",
|
|
35
|
+
"procedural"
|
|
36
|
+
],
|
|
37
|
+
"prefix": "exercise:",
|
|
38
|
+
"check": "exercise",
|
|
39
|
+
"error": "Verification requires a linked passing practice exercise, a compatibility context, and explicit review."
|
|
40
|
+
}
|
|
41
|
+
},
|
|
25
42
|
"migration3": "CREATE TABLE skill_proposals (id TEXT PRIMARY KEY, context TEXT NOT NULL, title TEXT NOT NULL, markdown TEXT NOT NULL, sources TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending','approved','rejected','withdrawn')), created_at TEXT NOT NULL, decided_at TEXT, receipt TEXT);",
|
|
26
43
|
"migration2": "ALTER TABLE memories ADD COLUMN verification TEXT; CREATE INDEX memories_verified ON memories(status, updated_at);",
|
|
27
44
|
"migration": "CREATE TABLE memories (\n id TEXT PRIMARY KEY,\n type TEXT NOT NULL,\n title TEXT NOT NULL,\n learning TEXT NOT NULL,\n evidence TEXT NOT NULL,\n scope TEXT NOT NULL DEFAULT 'project' CHECK (scope = 'project'),\n status TEXT NOT NULL DEFAULT 'candidate',\n revision INTEGER NOT NULL DEFAULT 1,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n);\nCREATE TABLE memory_tombstones (id TEXT PRIMARY KEY, revision INTEGER NOT NULL, deleted_at TEXT NOT NULL);\nCREATE TABLE memory_index_state (id INTEGER PRIMARY KEY CHECK (id = 1), revision INTEGER NOT NULL, indexed_revision INTEGER NOT NULL);\nINSERT INTO memory_index_state VALUES (1, 0, -1);\nCREATE INDEX memories_status_updated ON memories (status, updated_at DESC);"
|
package/src/memory/index.js
CHANGED
|
@@ -1,259 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import { randomUUID } from "node:crypto";
|
|
4
|
-
import { chmod, lstat, mkdir, readFile, writeFile } from "node:fs/promises";
|
|
5
|
-
import { join, resolve } from "node:path";
|
|
6
|
-
|
|
7
|
-
const spec = JSON.parse(await readFile(new URL("./contract.json", import.meta.url), "utf8"));
|
|
8
|
-
const { limits } = spec;
|
|
9
|
-
const safeRef = /^[A-Za-z0-9][A-Za-z0-9_.:-]*$/;
|
|
10
|
-
const time = () => new Date().toISOString();
|
|
11
|
-
const queryTokens = value => value.toLowerCase().match(/[\p{L}\p{N}_]+/gu)?.slice(0, 12) ?? [];
|
|
12
|
-
|
|
13
|
-
function text(value, max, name) {
|
|
14
|
-
if (typeof value !== "string" || !value.trim() || [...value.trim()].length > max || value.includes("\0")) {
|
|
15
|
-
throw new Error(name + " must contain 1–" + max + " characters.");
|
|
16
|
-
}
|
|
17
|
-
return value.trim();
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
function record(value) {
|
|
21
|
-
if (!spec.types.includes(value?.type)) throw new Error("Choose episodic, semantic, procedural, or corrective memory.");
|
|
22
|
-
const evidence = value.evidence ?? [];
|
|
23
|
-
if (!Array.isArray(evidence) || evidence.length > limits.evidence ||
|
|
24
|
-
evidence.some(item => typeof item !== "string" || item.length > limits.id || !safeRef.test(item))) {
|
|
25
|
-
throw new Error("Use up to 16 evidence IDs, such as run:abc123.");
|
|
26
|
-
}
|
|
27
|
-
return {
|
|
28
|
-
type: value.type, title: text(value.title, limits.title, "Title"),
|
|
29
|
-
learning: text(value.learning, limits.learning, "Learning"), evidence: [...new Set(evidence)],
|
|
30
|
-
};
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
function present(row) {
|
|
34
|
-
return row ? { id: row.id, type: row.type, title: row.title, learning: row.learning,
|
|
35
|
-
evidence: JSON.parse(row.evidence), scope: row.scope, status: row.status, revision: row.revision,
|
|
36
|
-
createdAt: row.created_at, updatedAt: row.updated_at, ...(row.verification ? { verification: JSON.parse(row.verification) } : {}) } : null;
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
function bounded(limit) {
|
|
40
|
-
if (!Number.isInteger(limit) || limit < 1 || limit > limits.results) throw new Error("Limit must be between 1 and 100.");
|
|
41
|
-
return limit;
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
async function directory(root) {
|
|
45
|
-
let path = resolve(root);
|
|
46
|
-
for (const part of [".lyra", "memory"]) {
|
|
47
|
-
path = join(path, part);
|
|
48
|
-
await mkdir(path, { mode: 0o700 }).catch(error => { if (error.code !== "EEXIST") throw error; });
|
|
49
|
-
if (!(await lstat(path)).isDirectory()) throw new Error("Memory folders must be regular directories.");
|
|
50
|
-
}
|
|
51
|
-
await chmod(path, 0o700);
|
|
52
|
-
await writeFile(join(path, ".gitignore"), "*\n", { flag: "wx", mode: 0o600 })
|
|
53
|
-
.catch(error => { if (error.code !== "EEXIST") throw error; });
|
|
54
|
-
return path;
|
|
55
|
-
}
|
|
1
|
+
import { openLocalMemoryStore } from "./local-store.js";
|
|
2
|
+
import { cloudSyncActions } from "./cloud-sync-actions.js";
|
|
56
3
|
|
|
57
4
|
export async function openMemoryStore(root = process.cwd(), { forceKeyword = false } = {}) {
|
|
58
5
|
if (process.env.LYRA_MEMORY === "off") throw new Error("Local memory is disabled by LYRA_MEMORY=off.");
|
|
59
|
-
|
|
60
|
-
const file = join(dir, "memory.db");
|
|
61
|
-
await writeFile(file, "", { flag: "wx", mode: 0o600 })
|
|
62
|
-
.catch(error => { if (error.code !== "EEXIST") throw error; });
|
|
63
|
-
if (!(await lstat(file)).isFile()) throw new Error("The memory database must be a regular file.");
|
|
64
|
-
await chmod(file, 0o600);
|
|
65
|
-
const { DatabaseSync } = await import("node:sqlite");
|
|
66
|
-
const db = new DatabaseSync(file);
|
|
67
|
-
function transaction(fn) {
|
|
68
|
-
db.exec("BEGIN IMMEDIATE");
|
|
69
|
-
try {
|
|
70
|
-
const result = fn();
|
|
71
|
-
db.exec("COMMIT");
|
|
72
|
-
return result;
|
|
73
|
-
} catch (error) {
|
|
74
|
-
db.exec("ROLLBACK");
|
|
75
|
-
throw error;
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
let fts = false;
|
|
79
|
-
try {
|
|
80
|
-
db.exec("PRAGMA busy_timeout = 3000");
|
|
81
|
-
transaction(() => {
|
|
82
|
-
const { user_version: version } = db.prepare("PRAGMA user_version").get();
|
|
83
|
-
const { application_id: app } = db.prepare("PRAGMA application_id").get();
|
|
84
|
-
if (version > spec.version) throw new Error("Update AgentLyra before opening this newer memory database.");
|
|
85
|
-
if ((app !== 0 && app !== spec.applicationId) || (version !== 0 && app !== spec.applicationId) ||
|
|
86
|
-
(version === 0 && db.prepare("SELECT 1 FROM sqlite_schema WHERE name NOT LIKE 'sqlite_%' LIMIT 1").get())) {
|
|
87
|
-
throw new Error("The file is not an AgentLyra memory database.");
|
|
88
|
-
}
|
|
89
|
-
if (version === 0) db.exec(spec.migration + "PRAGMA application_id = " + spec.applicationId);
|
|
90
|
-
if (version < 2) db.exec(spec.migration2);
|
|
91
|
-
if (version < 3) db.exec(spec.migration3);
|
|
92
|
-
if (version < 4) db.exec(spec.migration4 + "PRAGMA user_version = 4");
|
|
93
|
-
});
|
|
94
|
-
db.exec("PRAGMA journal_mode = WAL; PRAGMA secure_delete = ON");
|
|
95
|
-
if (!forceKeyword) {
|
|
96
|
-
try {
|
|
97
|
-
db.exec("CREATE VIRTUAL TABLE IF NOT EXISTS memory_fts USING fts5(id UNINDEXED, title, learning)");
|
|
98
|
-
fts = true;
|
|
99
|
-
} catch (error) {
|
|
100
|
-
if (!/no such module: fts5/i.test(error.message)) throw error;
|
|
101
|
-
}
|
|
102
|
-
}
|
|
103
|
-
} catch (error) { db.close(); throw error; }
|
|
104
|
-
|
|
105
|
-
const get = id => present(db.prepare("SELECT * FROM memories WHERE id = ?").get(id));
|
|
106
|
-
const dirty = () => db.exec("UPDATE memory_index_state SET revision = revision + 1 WHERE id = 1");
|
|
107
|
-
const syncBase = id => {
|
|
108
|
-
const item = get(id);
|
|
109
|
-
const tombstone = db.prepare("SELECT revision FROM memory_tombstones WHERE id=?").get(id);
|
|
110
|
-
const link = db.prepare("SELECT * FROM memory_cloud_links WHERE id=?").get(id) ?? null;
|
|
111
|
-
return { item, deleted: Boolean(tombstone), revision: item?.revision ?? tombstone?.revision ?? 0, link };
|
|
112
|
-
};
|
|
113
|
-
const saveLink = (remote, revision) => {
|
|
114
|
-
db.prepare("INSERT INTO memory_cloud_links VALUES (?,?,?,?) ON CONFLICT(id) DO UPDATE SET " +
|
|
115
|
-
"cloud_revision=excluded.cloud_revision,local_revision=excluded.local_revision " +
|
|
116
|
-
"WHERE cloud_account=excluded.cloud_account AND cloud_revision<=excluded.cloud_revision")
|
|
117
|
-
.run(remote.id, remote.revision, revision, remote.account);
|
|
118
|
-
};
|
|
119
|
-
const erase = (id, revision) => {
|
|
120
|
-
db.prepare("INSERT INTO memory_tombstones VALUES (?,?,?) ON CONFLICT(id) DO NOTHING").run(id, revision, time());
|
|
121
|
-
if (fts) db.prepare("DELETE FROM memory_fts WHERE id=?").run(id);
|
|
122
|
-
db.prepare("DELETE FROM skill_proposals WHERE EXISTS (SELECT 1 FROM json_each(sources) WHERE json_extract(value, '$.id')=?)").run(id);
|
|
123
|
-
db.prepare("DELETE FROM memories WHERE id=?").run(id);
|
|
124
|
-
dirty();
|
|
125
|
-
};
|
|
126
|
-
return {
|
|
127
|
-
syncBase,
|
|
128
|
-
rememberCloudRevision: (remote, revision) => transaction(() => saveLink(remote, revision)),
|
|
129
|
-
applyCloudMemory(remote, expected, choice) {
|
|
130
|
-
return transaction(() => {
|
|
131
|
-
const local = syncBase(remote.id);
|
|
132
|
-
if (local.revision !== expected.revision ||
|
|
133
|
-
local.link?.cloud_revision !== expected.link?.cloud_revision ||
|
|
134
|
-
local.link?.cloud_account !== expected.link?.cloud_account) {
|
|
135
|
-
throw new Error("The local record changed during sync. Pull again.");
|
|
136
|
-
}
|
|
137
|
-
if (local.link?.cloud_revision === remote.revision) return { id: remote.id, updated: false };
|
|
138
|
-
const different = local.link ? local.revision !== local.link.local_revision : local.revision !== 0;
|
|
139
|
-
if (different && !(local.deleted && remote.deleted)) {
|
|
140
|
-
if (!choice || local.deleted || remote.deleted || !local.item) throw new Error("Both copies changed. Review before syncing.");
|
|
141
|
-
if (choice === "local") {
|
|
142
|
-
saveLink(remote, 0);
|
|
143
|
-
return { id: remote.id, keptLocal: true };
|
|
144
|
-
}
|
|
145
|
-
}
|
|
146
|
-
if (remote.deleted) {
|
|
147
|
-
if (!local.deleted) erase(remote.id, local.revision + 1);
|
|
148
|
-
saveLink(remote, syncBase(remote.id).revision);
|
|
149
|
-
return { id: remote.id, deleted: true };
|
|
150
|
-
}
|
|
151
|
-
if (local.deleted) throw new Error("This memory was forgotten locally. It cannot be restored by a pull.");
|
|
152
|
-
const incoming = record(remote.memory);
|
|
153
|
-
if (!eligibleText([incoming.title, incoming.learning, ...incoming.evidence].join(" "))) {
|
|
154
|
-
throw new Error("The remote memory contains unsafe content.");
|
|
155
|
-
}
|
|
156
|
-
if (!local.item && db.prepare("SELECT count(*) AS count FROM memories").get().count >= limits.records) {
|
|
157
|
-
throw new Error("Memory is full. Forget a record before importing one.");
|
|
158
|
-
}
|
|
159
|
-
const now = time();
|
|
160
|
-
const revision = local.revision + 1;
|
|
161
|
-
db.prepare("INSERT INTO memories (id,type,title,learning,evidence,revision,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?) " +
|
|
162
|
-
"ON CONFLICT(id) DO UPDATE SET type=excluded.type,title=excluded.title,learning=excluded.learning,evidence=excluded.evidence," +
|
|
163
|
-
"revision=excluded.revision,updated_at=excluded.updated_at,status='candidate',verification=NULL")
|
|
164
|
-
.run(remote.id, incoming.type, incoming.title, incoming.learning, JSON.stringify(incoming.evidence), revision, now, now);
|
|
165
|
-
dirty();
|
|
166
|
-
saveLink(remote, revision);
|
|
167
|
-
return { id: remote.id, updated: true, status: "candidate" };
|
|
168
|
-
});
|
|
169
|
-
},
|
|
170
|
-
...proposalActions(db, transaction),
|
|
171
|
-
file,
|
|
172
|
-
close: () => db.close(),
|
|
173
|
-
get,
|
|
174
|
-
list(limit = 20) {
|
|
175
|
-
return db.prepare("SELECT * FROM memories ORDER BY updated_at DESC, id LIMIT ?").all(bounded(limit)).map(present);
|
|
176
|
-
},
|
|
177
|
-
record(value) {
|
|
178
|
-
const item = record(value);
|
|
179
|
-
return transaction(() => {
|
|
180
|
-
if (db.prepare("SELECT count(*) AS count FROM memories").get().count >= limits.records) {
|
|
181
|
-
throw new Error("Memory is full. Forget a record before adding one.");
|
|
182
|
-
}
|
|
183
|
-
const id = randomUUID();
|
|
184
|
-
const now = time();
|
|
185
|
-
db.prepare("INSERT INTO memories (id,type,title,learning,evidence,created_at,updated_at) VALUES (?,?,?,?,?,?,?)")
|
|
186
|
-
.run(id, item.type, item.title, item.learning, JSON.stringify(item.evidence), now, now);
|
|
187
|
-
dirty();
|
|
188
|
-
return get(id);
|
|
189
|
-
});
|
|
190
|
-
},
|
|
191
|
-
search(query, limit = 20) {
|
|
192
|
-
bounded(limit);
|
|
193
|
-
const tokens = queryTokens(text(query, 240, "Query"));
|
|
194
|
-
if (!tokens.length) return [];
|
|
195
|
-
if (!fts) {
|
|
196
|
-
const terms = tokens.map(() => "instr(lower(title || ' ' || learning), ?) > 0").join(" AND ");
|
|
197
|
-
return db.prepare("SELECT * FROM memories WHERE status != 'archived' AND " + terms + " ORDER BY updated_at DESC, id LIMIT ?")
|
|
198
|
-
.all(...tokens, limit).map(present);
|
|
199
|
-
}
|
|
200
|
-
return transaction(() => {
|
|
201
|
-
const state = db.prepare("SELECT revision, indexed_revision FROM memory_index_state WHERE id=1").get();
|
|
202
|
-
if (state.revision !== state.indexed_revision) {
|
|
203
|
-
db.exec("DELETE FROM memory_fts; INSERT INTO memory_fts SELECT id,title,learning FROM memories;" +
|
|
204
|
-
"UPDATE memory_index_state SET indexed_revision=revision WHERE id=1");
|
|
205
|
-
}
|
|
206
|
-
const expression = tokens.map(token => '"' + token + '"').join(" AND ");
|
|
207
|
-
return db.prepare("SELECT memories.* FROM memory_fts JOIN memories ON memories.id = memory_fts.id " +
|
|
208
|
-
"WHERE memory_fts MATCH ? AND memories.status != 'archived' ORDER BY bm25(memory_fts), memories.id LIMIT ?").all(expression, limit).map(present);
|
|
209
|
-
});
|
|
210
|
-
},
|
|
211
|
-
verify(id, evidence) {
|
|
212
|
-
return transaction(() => {
|
|
213
|
-
const receipt = reviewEvidence(get(id), evidence);
|
|
214
|
-
db.prepare("UPDATE memories SET status='verified', verification=?, revision=revision+1, updated_at=? WHERE id=?")
|
|
215
|
-
.run(JSON.stringify(receipt), time(), id);
|
|
216
|
-
return get(id);
|
|
217
|
-
});
|
|
218
|
-
},
|
|
219
|
-
retrieve(query, context, adapter = "coding") {
|
|
220
|
-
if (!safeContext(context) || !hasMemoryAdapter(adapter)) return [];
|
|
221
|
-
const tokens = new Set(queryTokens(query).filter(token => token.length >= 4));
|
|
222
|
-
if (!tokens.size) return [];
|
|
223
|
-
const result = [];
|
|
224
|
-
let remaining = 2400;
|
|
225
|
-
const rows = db.prepare("SELECT * FROM memories WHERE status='verified' AND json_extract(verification, '$.context') = ? AND json_extract(verification, '$.adapter') = ? ORDER BY updated_at DESC, id LIMIT 100").all(context, adapter);
|
|
226
|
-
for (const row of rows) {
|
|
227
|
-
const item = present(row);
|
|
228
|
-
const body = item.title + " " + item.learning;
|
|
229
|
-
if (!eligibleText(body) || !queryTokens(body).some(token => tokens.has(token)) || body.length > remaining) continue;
|
|
230
|
-
result.push(item);
|
|
231
|
-
remaining -= body.length;
|
|
232
|
-
if (result.length === 4) break;
|
|
233
|
-
}
|
|
234
|
-
return result;
|
|
235
|
-
},
|
|
236
|
-
archive(id) {
|
|
237
|
-
return transaction(() => {
|
|
238
|
-
const item = get(id);
|
|
239
|
-
if (!item || item.status === "archived") return item;
|
|
240
|
-
db.prepare("UPDATE memories SET status = 'archived', revision = revision + 1, updated_at = ? WHERE id = ?")
|
|
241
|
-
.run(time(), id);
|
|
242
|
-
return get(id);
|
|
243
|
-
});
|
|
244
|
-
},
|
|
245
|
-
stats() {
|
|
246
|
-
const counts = Object.fromEntries(spec.statuses.map(status => [status, 0]));
|
|
247
|
-
for (const row of db.prepare("SELECT status, count(*) AS count FROM memories GROUP BY status").all()) counts[row.status] = row.count;
|
|
248
|
-
return { schemaVersion: spec.version, search: fts ? "fts5" : "keyword", ...counts };
|
|
249
|
-
},
|
|
250
|
-
forget(id) {
|
|
251
|
-
return transaction(() => {
|
|
252
|
-
const item = get(id);
|
|
253
|
-
if (!item) return false;
|
|
254
|
-
erase(id, item.revision + 1);
|
|
255
|
-
return true;
|
|
256
|
-
});
|
|
257
|
-
},
|
|
258
|
-
};
|
|
6
|
+
return openLocalMemoryStore(root, { forceKeyword, namespace: ".lyra", extension: cloudSyncActions });
|
|
259
7
|
}
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
import { proposalActions } from "./proposals.js";
|
|
2
|
+
import { reviewEvidence, eligibleText, hasMemoryAdapter, safeContext } from "./validation.js";
|
|
3
|
+
import { randomUUID } from "node:crypto";
|
|
4
|
+
import { chmod, lstat, mkdir, readFile, writeFile } from "node:fs/promises";
|
|
5
|
+
import { join, resolve } from "node:path";
|
|
6
|
+
|
|
7
|
+
const spec = JSON.parse(await readFile(new URL("./contract.json", import.meta.url), "utf8"));
|
|
8
|
+
const { limits } = spec;
|
|
9
|
+
const safeRef = /^[A-Za-z0-9][A-Za-z0-9_.:-]*$/;
|
|
10
|
+
const time = () => new Date().toISOString();
|
|
11
|
+
const queryTokens = value => value.toLowerCase().match(/[\p{L}\p{N}_]+/gu)?.slice(0, 12) ?? [];
|
|
12
|
+
|
|
13
|
+
function text(value, max, name) {
|
|
14
|
+
if (typeof value !== "string" || !value.trim() || [...value.trim()].length > max || value.includes("\0")) {
|
|
15
|
+
throw new Error(name + " must contain 1–" + max + " characters.");
|
|
16
|
+
}
|
|
17
|
+
return value.trim();
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function record(value) {
|
|
21
|
+
if (!spec.types.includes(value?.type)) throw new Error("Choose episodic, semantic, procedural, or corrective memory.");
|
|
22
|
+
const evidence = value.evidence ?? [];
|
|
23
|
+
if (!Array.isArray(evidence) || evidence.length > limits.evidence ||
|
|
24
|
+
evidence.some(item => typeof item !== "string" || item.length > limits.id || !safeRef.test(item))) {
|
|
25
|
+
throw new Error("Use up to 16 evidence IDs, such as run:abc123.");
|
|
26
|
+
}
|
|
27
|
+
return {
|
|
28
|
+
type: value.type, title: text(value.title, limits.title, "Title"),
|
|
29
|
+
learning: text(value.learning, limits.learning, "Learning"), evidence: [...new Set(evidence)],
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function present(row) {
|
|
34
|
+
return row ? { id: row.id, type: row.type, title: row.title, learning: row.learning,
|
|
35
|
+
evidence: JSON.parse(row.evidence), scope: row.scope, status: row.status, revision: row.revision,
|
|
36
|
+
createdAt: row.created_at, updatedAt: row.updated_at, ...(row.verification ? { verification: JSON.parse(row.verification) } : {}) } : null;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function bounded(limit) {
|
|
40
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > limits.results) throw new Error("Limit must be between 1 and 100.");
|
|
41
|
+
return limit;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async function directory(root, namespace) {
|
|
45
|
+
let path = resolve(root);
|
|
46
|
+
for (const part of [namespace, "memory"]) {
|
|
47
|
+
path = join(path, part);
|
|
48
|
+
await mkdir(path, { mode: 0o700 }).catch(error => { if (error.code !== "EEXIST") throw error; });
|
|
49
|
+
if (!(await lstat(path)).isDirectory()) throw new Error("Memory folders must be regular directories.");
|
|
50
|
+
}
|
|
51
|
+
await chmod(path, 0o700);
|
|
52
|
+
await writeFile(join(path, ".gitignore"), "*\n", { flag: "wx", mode: 0o600 })
|
|
53
|
+
.catch(error => { if (error.code !== "EEXIST") throw error; });
|
|
54
|
+
return path;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export async function openLocalMemoryStore(root = process.cwd(), { forceKeyword = false, namespace = ".memory-engine", extension } = {}) {
|
|
58
|
+
if (!/^\.[A-Za-z0-9][A-Za-z0-9_-]*$/.test(namespace)) throw new Error("Invalid memory namespace.");
|
|
59
|
+
const dir = await directory(root, namespace);
|
|
60
|
+
const file = join(dir, "memory.db");
|
|
61
|
+
await writeFile(file, "", { flag: "wx", mode: 0o600 })
|
|
62
|
+
.catch(error => { if (error.code !== "EEXIST") throw error; });
|
|
63
|
+
if (!(await lstat(file)).isFile()) throw new Error("The memory database must be a regular file.");
|
|
64
|
+
await chmod(file, 0o600);
|
|
65
|
+
const { DatabaseSync } = await import("node:sqlite");
|
|
66
|
+
const db = new DatabaseSync(file);
|
|
67
|
+
function transaction(fn) {
|
|
68
|
+
db.exec("BEGIN IMMEDIATE");
|
|
69
|
+
try {
|
|
70
|
+
const result = fn();
|
|
71
|
+
db.exec("COMMIT");
|
|
72
|
+
return result;
|
|
73
|
+
} catch (error) {
|
|
74
|
+
db.exec("ROLLBACK");
|
|
75
|
+
throw error;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
let fts = false;
|
|
79
|
+
try {
|
|
80
|
+
db.exec("PRAGMA busy_timeout = 3000");
|
|
81
|
+
transaction(() => {
|
|
82
|
+
const { user_version: version } = db.prepare("PRAGMA user_version").get();
|
|
83
|
+
const { application_id: app } = db.prepare("PRAGMA application_id").get();
|
|
84
|
+
if (version > spec.version) throw new Error("Update the memory engine before opening this newer memory database.");
|
|
85
|
+
if ((app !== 0 && app !== spec.applicationId) || (version !== 0 && app !== spec.applicationId) ||
|
|
86
|
+
(version === 0 && db.prepare("SELECT 1 FROM sqlite_schema WHERE name NOT LIKE 'sqlite_%' LIMIT 1").get())) {
|
|
87
|
+
throw new Error("The file is not a compatible memory database.");
|
|
88
|
+
}
|
|
89
|
+
if (version === 0) db.exec(spec.migration + "PRAGMA application_id = " + spec.applicationId);
|
|
90
|
+
if (version < 2) db.exec(spec.migration2);
|
|
91
|
+
if (version < 3) db.exec(spec.migration3);
|
|
92
|
+
if (version < 4) db.exec("PRAGMA user_version = 4");
|
|
93
|
+
});
|
|
94
|
+
db.exec("PRAGMA journal_mode = WAL; PRAGMA secure_delete = ON");
|
|
95
|
+
if (!forceKeyword) {
|
|
96
|
+
try {
|
|
97
|
+
db.exec("CREATE VIRTUAL TABLE IF NOT EXISTS memory_fts USING fts5(id UNINDEXED, title, learning)");
|
|
98
|
+
fts = true;
|
|
99
|
+
} catch (error) {
|
|
100
|
+
if (!/no such module: fts5/i.test(error.message)) throw error;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
} catch (error) { db.close(); throw error; }
|
|
104
|
+
|
|
105
|
+
const get = id => present(db.prepare("SELECT * FROM memories WHERE id = ?").get(id));
|
|
106
|
+
const dirty = () => db.exec("UPDATE memory_index_state SET revision = revision + 1 WHERE id = 1");
|
|
107
|
+
const erase = (id, revision) => {
|
|
108
|
+
db.prepare("INSERT INTO memory_tombstones VALUES (?,?,?) ON CONFLICT(id) DO NOTHING").run(id, revision, time());
|
|
109
|
+
if (fts) db.prepare("DELETE FROM memory_fts WHERE id=?").run(id);
|
|
110
|
+
db.prepare("DELETE FROM skill_proposals WHERE EXISTS (SELECT 1 FROM json_each(sources) WHERE json_extract(value, '$.id')=?)").run(id);
|
|
111
|
+
db.prepare("DELETE FROM memories WHERE id=?").run(id);
|
|
112
|
+
dirty();
|
|
113
|
+
};
|
|
114
|
+
let extensions;
|
|
115
|
+
try {
|
|
116
|
+
extensions = extension?.({ db, transaction, get, erase, dirty, record, eligibleText, limits, time }) ?? {};
|
|
117
|
+
} catch (error) { db.close(); throw error; }
|
|
118
|
+
return {
|
|
119
|
+
...extensions,
|
|
120
|
+
...proposalActions(db, transaction),
|
|
121
|
+
file,
|
|
122
|
+
close: () => db.close(),
|
|
123
|
+
get,
|
|
124
|
+
list(limit = 20) {
|
|
125
|
+
return db.prepare("SELECT * FROM memories ORDER BY updated_at DESC, id LIMIT ?").all(bounded(limit)).map(present);
|
|
126
|
+
},
|
|
127
|
+
record(value) {
|
|
128
|
+
const item = record(value);
|
|
129
|
+
return transaction(() => {
|
|
130
|
+
if (db.prepare("SELECT count(*) AS count FROM memories").get().count >= limits.records) {
|
|
131
|
+
throw new Error("Memory is full. Forget a record before adding one.");
|
|
132
|
+
}
|
|
133
|
+
const id = randomUUID();
|
|
134
|
+
const now = time();
|
|
135
|
+
db.prepare("INSERT INTO memories (id,type,title,learning,evidence,created_at,updated_at) VALUES (?,?,?,?,?,?,?)")
|
|
136
|
+
.run(id, item.type, item.title, item.learning, JSON.stringify(item.evidence), now, now);
|
|
137
|
+
dirty();
|
|
138
|
+
return get(id);
|
|
139
|
+
});
|
|
140
|
+
},
|
|
141
|
+
search(query, limit = 20) {
|
|
142
|
+
bounded(limit);
|
|
143
|
+
const tokens = queryTokens(text(query, 240, "Query"));
|
|
144
|
+
if (!tokens.length) return [];
|
|
145
|
+
if (!fts) {
|
|
146
|
+
const terms = tokens.map(() => "instr(lower(title || ' ' || learning), ?) > 0").join(" AND ");
|
|
147
|
+
return db.prepare("SELECT * FROM memories WHERE status != 'archived' AND " + terms + " ORDER BY updated_at DESC, id LIMIT ?")
|
|
148
|
+
.all(...tokens, limit).map(present);
|
|
149
|
+
}
|
|
150
|
+
return transaction(() => {
|
|
151
|
+
const state = db.prepare("SELECT revision, indexed_revision FROM memory_index_state WHERE id=1").get();
|
|
152
|
+
if (state.revision !== state.indexed_revision) {
|
|
153
|
+
db.exec("DELETE FROM memory_fts; INSERT INTO memory_fts SELECT id,title,learning FROM memories;" +
|
|
154
|
+
"UPDATE memory_index_state SET indexed_revision=revision WHERE id=1");
|
|
155
|
+
}
|
|
156
|
+
const expression = tokens.map(token => '"' + token + '"').join(" AND ");
|
|
157
|
+
return db.prepare("SELECT memories.* FROM memory_fts JOIN memories ON memories.id = memory_fts.id " +
|
|
158
|
+
"WHERE memory_fts MATCH ? AND memories.status != 'archived' ORDER BY bm25(memory_fts), memories.id LIMIT ?").all(expression, limit).map(present);
|
|
159
|
+
});
|
|
160
|
+
},
|
|
161
|
+
verify(id, evidence) {
|
|
162
|
+
return transaction(() => {
|
|
163
|
+
const receipt = reviewEvidence(get(id), evidence);
|
|
164
|
+
db.prepare("UPDATE memories SET status='verified', verification=?, revision=revision+1, updated_at=? WHERE id=?")
|
|
165
|
+
.run(JSON.stringify(receipt), time(), id);
|
|
166
|
+
return get(id);
|
|
167
|
+
});
|
|
168
|
+
},
|
|
169
|
+
retrieve(query, context, adapter = "coding") {
|
|
170
|
+
if (!safeContext(context) || !hasMemoryAdapter(adapter)) return [];
|
|
171
|
+
const tokens = new Set(queryTokens(query).filter(token => token.length >= 4));
|
|
172
|
+
if (!tokens.size) return [];
|
|
173
|
+
const result = [];
|
|
174
|
+
let remaining = 2400;
|
|
175
|
+
const rows = db.prepare("SELECT * FROM memories WHERE status='verified' AND json_extract(verification, '$.context') = ? AND json_extract(verification, '$.adapter') = ? ORDER BY updated_at DESC, id LIMIT 100").all(context, adapter);
|
|
176
|
+
for (const row of rows) {
|
|
177
|
+
const item = present(row);
|
|
178
|
+
const body = item.title + " " + item.learning;
|
|
179
|
+
if (!eligibleText(body) || !queryTokens(body).some(token => tokens.has(token)) || body.length > remaining) continue;
|
|
180
|
+
result.push(item);
|
|
181
|
+
remaining -= body.length;
|
|
182
|
+
if (result.length === 4) break;
|
|
183
|
+
}
|
|
184
|
+
return result;
|
|
185
|
+
},
|
|
186
|
+
archive(id) {
|
|
187
|
+
return transaction(() => {
|
|
188
|
+
const item = get(id);
|
|
189
|
+
if (!item || item.status === "archived") return item;
|
|
190
|
+
db.prepare("UPDATE memories SET status = 'archived', revision = revision + 1, updated_at = ? WHERE id = ?")
|
|
191
|
+
.run(time(), id);
|
|
192
|
+
return get(id);
|
|
193
|
+
});
|
|
194
|
+
},
|
|
195
|
+
stats() {
|
|
196
|
+
const counts = Object.fromEntries(spec.statuses.map(status => [status, 0]));
|
|
197
|
+
for (const row of db.prepare("SELECT status, count(*) AS count FROM memories GROUP BY status").all()) counts[row.status] = row.count;
|
|
198
|
+
return { schemaVersion: spec.version, search: fts ? "fts5" : "keyword", ...counts };
|
|
199
|
+
},
|
|
200
|
+
forget(id) {
|
|
201
|
+
return transaction(() => {
|
|
202
|
+
const item = get(id);
|
|
203
|
+
if (!item) return false;
|
|
204
|
+
erase(id, item.revision + 1);
|
|
205
|
+
return true;
|
|
206
|
+
});
|
|
207
|
+
},
|
|
208
|
+
};
|
|
209
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "memory-engine-local",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"private": true,
|
|
5
|
+
"type": "module",
|
|
6
|
+
"description": "Standalone local memory engine (staging package)",
|
|
7
|
+
"engines": {
|
|
8
|
+
"node": ">=22.13.0"
|
|
9
|
+
},
|
|
10
|
+
"license": "MIT",
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"types": "./standalone.d.ts",
|
|
14
|
+
"default": "./standalone.js"
|
|
15
|
+
},
|
|
16
|
+
"./bridge": "./bridge.js"
|
|
17
|
+
},
|
|
18
|
+
"bin": {
|
|
19
|
+
"memory-engine": "./bridge-cli.js"
|
|
20
|
+
},
|
|
21
|
+
"files": [
|
|
22
|
+
"standalone.js",
|
|
23
|
+
"standalone.d.ts",
|
|
24
|
+
"local-store.js",
|
|
25
|
+
"contract.json",
|
|
26
|
+
"validation.js",
|
|
27
|
+
"proposals.js",
|
|
28
|
+
"bridge.js",
|
|
29
|
+
"bridge-cli.js",
|
|
30
|
+
"LICENSE",
|
|
31
|
+
"README.md"
|
|
32
|
+
]
|
|
33
|
+
}
|
package/src/memory/proposals.js
CHANGED
|
@@ -53,6 +53,12 @@ export function proposalActions(db, transaction) {
|
|
|
53
53
|
return get(id);
|
|
54
54
|
});
|
|
55
55
|
},
|
|
56
|
+
approvedSkills(context) {
|
|
57
|
+
if (!safeContext(context)) return [];
|
|
58
|
+
const sources = readSources(db, context);
|
|
59
|
+
return db.prepare("SELECT * FROM skill_proposals WHERE context=? AND status='approved' ORDER BY decided_at DESC,id LIMIT 100").all(context)
|
|
60
|
+
.map(present).filter(p => p.receipt && p.sources.every(s => sources.some(r => r.id === s.id && r.revision === s.revision && r.evidenceId === s.evidenceId)));
|
|
61
|
+
},
|
|
56
62
|
proposal: get,
|
|
57
63
|
proposals: () => db.prepare("SELECT * FROM skill_proposals ORDER BY created_at DESC,id LIMIT 100").all().map(present),
|
|
58
64
|
decideProposal(id, decision, evidence) {
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
export type MemoryType = "episodic" | "semantic" | "procedural" | "corrective";
|
|
2
|
+
export type MemoryStatus = "candidate" | "verified" | "archived";
|
|
3
|
+
export interface MemoryInput { type: MemoryType; title: string; learning: string; evidence?: string[] }
|
|
4
|
+
export type MemoryAdapter = "coding" | "practice";
|
|
5
|
+
export type VerificationReceipt = { evidenceId: string; context: string } & (
|
|
6
|
+
{ adapter: "coding"; test: string } | { adapter: "practice"; exercise: string }
|
|
7
|
+
);
|
|
8
|
+
export interface MemoryRecord extends MemoryInput {
|
|
9
|
+
id: string;
|
|
10
|
+
evidence: string[];
|
|
11
|
+
scope: "project";
|
|
12
|
+
status: MemoryStatus;
|
|
13
|
+
revision: number;
|
|
14
|
+
createdAt: string;
|
|
15
|
+
updatedAt: string;
|
|
16
|
+
verification?: VerificationReceipt;
|
|
17
|
+
}
|
|
18
|
+
export interface SkillProposalSource { id: string; revision: number; evidenceId: string }
|
|
19
|
+
export interface SkillProposalReceipt { evidenceId: string; context: string; result: "passed"; reviewed: true }
|
|
20
|
+
export interface SkillProposal {
|
|
21
|
+
id: string;
|
|
22
|
+
context: string;
|
|
23
|
+
title: string;
|
|
24
|
+
markdown: string;
|
|
25
|
+
sources: SkillProposalSource[];
|
|
26
|
+
status: "pending" | "approved" | "rejected" | "withdrawn";
|
|
27
|
+
createdAt: string;
|
|
28
|
+
decidedAt: string | null;
|
|
29
|
+
receipt: SkillProposalReceipt | null;
|
|
30
|
+
}
|
|
31
|
+
export interface MemoryStore {
|
|
32
|
+
readonly file: string;
|
|
33
|
+
consolidate(context: string): Array<{ title: string; learning: string; sources: SkillProposalSource[] }>;
|
|
34
|
+
propose(context: string, memoryId: string): SkillProposal;
|
|
35
|
+
proposal(id: string): SkillProposal | null;
|
|
36
|
+
proposals(): SkillProposal[];
|
|
37
|
+
approvedSkills(context: string): SkillProposal[];
|
|
38
|
+
decideProposal(id: string, decision: "approved" | "rejected" | "withdrawn", evidence?: SkillProposalReceipt): SkillProposal;
|
|
39
|
+
close(): void;
|
|
40
|
+
get(id: string): MemoryRecord | null;
|
|
41
|
+
list(limit?: number): MemoryRecord[];
|
|
42
|
+
record(value: MemoryInput): MemoryRecord;
|
|
43
|
+
search(query: string, limit?: number): MemoryRecord[];
|
|
44
|
+
stats(): { schemaVersion: number; search: "fts5" | "keyword" } & Record<MemoryStatus, number>;
|
|
45
|
+
verify(id: string, evidence: VerificationReceipt & { result: "passed"; reviewed: true }): MemoryRecord;
|
|
46
|
+
retrieve(query: string, context: string, adapter?: MemoryAdapter): MemoryRecord[];
|
|
47
|
+
archive(id: string): MemoryRecord | null;
|
|
48
|
+
forget(id: string): boolean;
|
|
49
|
+
}
|
|
50
|
+
export function openLocalMemoryStore(root?: string, options?: { forceKeyword?: boolean; namespace?: string }): Promise<MemoryStore>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { openLocalMemoryStore } from "./local-store.js";
|
package/src/runtime/run-agent.js
CHANGED
|
@@ -1,22 +1,30 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
2
|
|
|
3
|
+
const frameworkFailures = {
|
|
4
|
+
FRAMEWORK_TIMEOUT: ["timeout", "Framework run timed out."],
|
|
5
|
+
FRAMEWORK_DEPENDENCY: ["missing_dependency", "Install the framework in the selected Python environment."],
|
|
6
|
+
FRAMEWORK_OUTPUT: ["invalid_output", "Framework agent returned an invalid output."],
|
|
7
|
+
};
|
|
8
|
+
|
|
3
9
|
/**
|
|
4
10
|
* @param {{
|
|
5
11
|
* agentId: string,
|
|
6
12
|
* request: import("./contracts.js").ModelRequest,
|
|
7
13
|
* provider: import("./contracts.js").ModelProvider,
|
|
8
14
|
* store: import("./contracts.js").RunStore,
|
|
15
|
+
* traceId?: string, framework?: string, revision?: string,
|
|
9
16
|
* onStarted?: (runId: string) => void,
|
|
10
17
|
* }} options
|
|
11
18
|
*/
|
|
12
|
-
export async function runAgent({ agentId, request, provider, store, onStarted }) {
|
|
19
|
+
export async function runAgent({ agentId, request, provider, store, onStarted, traceId, framework, revision }) {
|
|
13
20
|
const runId = randomUUID();
|
|
21
|
+
const started = Date.now();
|
|
14
22
|
/** @param {number} seq */
|
|
15
|
-
const envelope = (seq) => ({ id: randomUUID(), run_id: runId, seq, ts: new Date().toISOString() });
|
|
23
|
+
const envelope = (seq) => ({ id: randomUUID(), run_id: runId, seq, ts: new Date().toISOString(), ...(traceId ? { schemaVersion: 1, trace_id: traceId } : {}) });
|
|
16
24
|
await store.append({
|
|
17
25
|
...envelope(0),
|
|
18
26
|
type: "run.started",
|
|
19
|
-
data: { agentId, model: request.model },
|
|
27
|
+
data: { agentId, model: request.model, ...(framework ? { framework, revision, execution: "local" } : {}) },
|
|
20
28
|
});
|
|
21
29
|
onStarted?.(runId);
|
|
22
30
|
|
|
@@ -24,11 +32,13 @@ export async function runAgent({ agentId, request, provider, store, onStarted })
|
|
|
24
32
|
let result;
|
|
25
33
|
try {
|
|
26
34
|
result = await provider.complete(request);
|
|
27
|
-
} catch {
|
|
35
|
+
} catch (error) {
|
|
36
|
+
const [reason, message] = Object.hasOwn(frameworkFailures, error?.code)
|
|
37
|
+
? frameworkFailures[error.code] : ["execution_error", "Framework execution failed."];
|
|
28
38
|
const failed = /** @type {const} */ ({
|
|
29
39
|
...envelope(1),
|
|
30
40
|
type: "run.failed",
|
|
31
|
-
data: { message: "Model request failed." },
|
|
41
|
+
data: { message: framework ? message : "Model request failed.", ...(framework ? { durationMs: Date.now() - started, reason } : {}) },
|
|
32
42
|
});
|
|
33
43
|
await store.append(failed);
|
|
34
44
|
return failed;
|
|
@@ -38,6 +48,6 @@ export async function runAgent({ agentId, request, provider, store, onStarted })
|
|
|
38
48
|
type: "run.completed",
|
|
39
49
|
data: { result },
|
|
40
50
|
});
|
|
41
|
-
await store.append(completed);
|
|
51
|
+
await store.append(framework ? { ...completed, data: { durationMs: Date.now() - started } } : completed);
|
|
42
52
|
return completed;
|
|
43
53
|
}
|