@knowall-ai/reverie
Version:
Reverie — graph memory that dreams. Graph-based memory system for AI agents. Store people, places, organizations as nodes. Build semantic relationships (KNOWS, WORKS_AT, CREATED). Hybrid keyword + semantic search finds partial matches and close variants.
183 lines (182 loc) • 6.82 kB
JavaScript
import { cypherIdentifier } from './types.js';
import neo4j, { Integer, Node, Relationship } from 'neo4j-driver';
const CLOSE_TIMEOUT_MS = 5_000;
/** session.close() awaits connection release with no deadline; a stuck release must not hang a tool call. */
async function closeBounded(session) {
let timer;
const deadline = new Promise((resolve) => { timer = setTimeout(resolve, CLOSE_TIMEOUT_MS); });
try {
await Promise.race([session.close().catch(() => undefined), deadline]);
}
finally {
clearTimeout(timer);
}
}
export class Neo4jClient {
driver;
database;
constructor(uri, username, password, database) {
this.driver = neo4j.driver(uri, neo4j.auth.basic(username, password));
this.database = database;
}
convertNestedIntegers(value) {
if (value instanceof Integer) {
return value.toNumber();
}
if (value instanceof Node) {
return {
...this.convertNestedIntegers(value.properties),
_id: value.identity.toNumber(),
_labels: value.labels,
};
}
if (value instanceof Relationship) {
return {
...this.convertNestedIntegers(value.properties),
_id: value.identity.toNumber(),
_type: value.type,
_start: value.start.toNumber(),
_end: value.end.toNumber(),
};
}
if (neo4j.isPath(value)) {
return {
start: this.convertNestedIntegers(value.start),
end: this.convertNestedIntegers(value.end),
segments: value.segments.map((segment) => ({
start: this.convertNestedIntegers(segment.start),
relationship: this.convertNestedIntegers(segment.relationship),
end: this.convertNestedIntegers(segment.end),
})),
};
}
if (neo4j.isPoint(value)) {
return { srid: this.convertNestedIntegers(value.srid), x: value.x, y: value.y, z: value.z };
}
if (neo4j.isDate(value) || neo4j.isDateTime(value) || neo4j.isLocalDateTime(value) ||
neo4j.isTime(value) || neo4j.isLocalTime(value) || neo4j.isDuration(value)) {
return value.toString();
}
if (Array.isArray(value)) {
return value.map((item) => this.convertNestedIntegers(item));
}
if (value && typeof value === 'object' && value.constructor === Object) {
const converted = {};
for (const [key, val] of Object.entries(value)) {
converted[key] = this.convertNestedIntegers(val);
}
return converted;
}
return value;
}
recordToObject(record) {
const obj = {};
for (const key of record.keys) {
obj[key] = this.convertNestedIntegers(record.get(key));
}
return obj;
}
async executeQuery(query, params = {}) {
const session = this.driver.session({
database: this.database
});
try {
const result = await session.run(query, params);
return result.records.map((record) => this.recordToObject(record));
}
finally {
await closeBounded(session);
}
}
/**
* Caller-supplied Cypher: runs in a READ transaction (the server rejects writes), stops
* consuming after `limit` records instead of materialising the whole result, and is
* bounded by a transaction timeout.
*/
async executeReadQuery(query, params, options) {
if (!Number.isSafeInteger(options.limit) || options.limit < 0) {
throw new Error('Query limit must be a non-negative integer');
}
if (options.limit === 0) {
return [];
}
const session = this.driver.session({
database: this.database,
defaultAccessMode: neo4j.session.READ
});
try {
return await session.executeRead(async (tx) => {
const rows = [];
for await (const record of tx.run(query, params)) {
rows.push(this.recordToObject(record));
if (rows.length >= options.limit) {
break;
}
}
return rows;
}, { timeout: options.timeoutMs });
}
finally {
await closeBounded(session);
}
}
async getNodes(label) {
return this.executeQuery(`MATCH (n:${cypherIdentifier(label)}) RETURN n as memory`);
}
async createNode(label, properties) {
const result = await this.executeQuery(`CREATE (n:${cypherIdentifier(label)} $props) RETURN n as memory`, { props: properties });
return result[0];
}
async createRelationship(fromNodeId, toNodeId, relationType, properties = {}) {
const result = await this.executeQuery(`MATCH (a), (b)
WHERE id(a) = $fromId AND id(b) = $toId
CREATE (a)-[r:${cypherIdentifier(relationType)} $props]->(b)
RETURN r as relationship`, {
fromId: neo4j.int(fromNodeId),
toId: neo4j.int(toNodeId),
props: properties,
});
return result[0];
}
async updateNode(nodeId, properties) {
const result = await this.executeQuery(`MATCH (n) WHERE id(n) = $nodeId
SET n += $props
RETURN n as memory`, {
nodeId: neo4j.int(nodeId),
props: properties,
});
return result[0];
}
async updateRelationship(fromNodeId, toNodeId, relationType, properties) {
const result = await this.executeQuery(`MATCH (a)-[r:${cypherIdentifier(relationType)}]->(b)
WHERE id(a) = $fromId AND id(b) = $toId
SET r += $props
RETURN r as relationship`, {
fromId: neo4j.int(fromNodeId),
toId: neo4j.int(toNodeId),
props: properties,
});
return result[0];
}
async deleteNode(nodeId) {
const result = await this.executeQuery(`MATCH (n) WHERE id(n) = $nodeId
DETACH DELETE n
RETURN count(n) as deletedCount`, {
nodeId: neo4j.int(nodeId),
});
return result[0];
}
async deleteRelationship(fromNodeId, toNodeId, relationType) {
const result = await this.executeQuery(`MATCH (a)-[r:${cypherIdentifier(relationType)}]->(b)
WHERE id(a) = $fromId AND id(b) = $toId
DELETE r
RETURN count(r) as deletedCount`, {
fromId: neo4j.int(fromNodeId),
toId: neo4j.int(toNodeId),
});
return result[0];
}
async close() {
await this.driver.close();
}
}