dsh-brain/lib/mnemon/driver.js

215 lines
9.3 KiB
JavaScript

/**
* LongMemory driver for Mnemon's Memory Spaces.
*
* Design rule (the whole point of this bridge): the cloud service is the
* source of truth. Every search/list/read/write is a live call to the
* user's own LongMemory endpoint — this driver keeps NO local replica of
* long-term memory, so anything another tool (Claude Code, Codex, the
* dashboard) wrote into LongMemory is visible inside DSH immediately.
*
* Connection resolution, per call:
* 1. the Mnemon connection for the space (service fields configured on
* the Mnemon page, plus the space's own `projectId`),
* 2. the injected `MemoryRemoteFactory` (cloud-sync bundle), which fills
* any endpoint/token the Mnemon side left empty from this package's
* settings sidecar — so a user who already configured dsh-brain
* configures nothing twice.
*
* A Memory Space maps to one LongMemory project; the empty project is the
* account-wide default scope.
*/
import { randomUUID } from 'node:crypto';
import { descriptor } from "./descriptor.js";
/** Epoch (ms, or seconds on older payloads) → ISO string, when plausible. */
function toIso(value) {
if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0)
return undefined;
const ms = value < 1e12 ? value * 1000 : value;
const date = new Date(ms);
return Number.isNaN(date.getTime()) ? undefined : date.toISOString();
}
/** Map one LongMemory hit onto a Mnemon Insight; unusable hits drop out. */
export function insightFromHit(hit) {
if (typeof hit.id !== 'string' || hit.id === '')
return undefined;
if (typeof hit.content !== 'string')
return undefined;
const insight = { id: hit.id, content: hit.content, source: 'external' };
if (typeof hit.primary_sector === 'string' && hit.primary_sector !== '') {
insight.category = hit.primary_sector;
}
if (Array.isArray(hit.tags)) {
const tags = hit.tags.filter((tag) => typeof tag === 'string');
if (tags.length > 0)
insight.tags = tags;
}
const createdAt = toIso(hit.created_at);
if (createdAt !== undefined)
insight.createdAt = createdAt;
const score = hit.score;
if (typeof score === 'number' && Number.isFinite(score))
insight.score = score;
return insight;
}
export class LongMemoryProvider {
authority;
options;
remoteFactory;
id = descriptor.id;
/** LongMemory scores are its own scale; the host may only order by them. */
scoreSemantics = { kind: 'provider-native' };
constructor(authority, options, remoteFactory) {
this.authority = authority;
this.options = options;
this.remoteFactory = remoteFactory;
}
/**
* Merge the space's Mnemon connection fields (authority first, the space
* record as fallback for older hosts). Fields left empty stay empty on
* purpose: the injected factory owns the package-settings fallback.
*/
resolve(body, direct) {
let connection = { ...(direct ?? {}) };
if (body !== undefined) {
if (this.authority !== undefined) {
try {
connection = { ...this.authority.providerConnection(body.id, descriptor.id), ...connection };
}
catch {
// Host could not resolve it; fall through to the space record.
}
}
const own = body.connection;
if (own !== null && typeof own === 'object' && !Array.isArray(own)) {
connection = { ...own, ...connection };
}
}
const endpoint = typeof connection.endpoint === 'string' && connection.endpoint !== ''
? connection.endpoint.replace(/\/+$/, '')
: undefined;
const token = typeof connection.token === 'string' && connection.token !== '' ? connection.token : undefined;
const projectId = typeof connection.projectId === 'string' && connection.projectId !== '' ? connection.projectId : undefined;
const timeoutMs = this.options.requestTimeoutMs;
return {
...(endpoint === undefined ? {} : { endpoint }),
...(token === undefined ? {} : { token }),
...(projectId === undefined ? {} : { projectId }),
...(timeoutMs === undefined ? {} : { timeoutMs }),
};
}
/** A remote bound to one resolved connection; the factory owns fallbacks. */
client(connection) {
return this.remoteFactory.forConnection(connection);
}
/** Enumerate the account's projects as Memory Spaces, plus the default scope. */
async discover(connection, signal) {
signal?.throwIfAborted();
const resolved = this.resolve(undefined, connection);
const result = await this.client(resolved).projects();
if (!result.ok) {
throw new Error(`LongMemory project discovery failed: ${result.error.message}`);
}
const spaces = [{
externalId: 'default',
name: 'LongMemory · 全部',
description: 'Account-wide default scope (no project filter).',
connection: {},
}];
for (const project of result.data.projects ?? []) {
if (typeof project.id !== 'string' || project.id === '')
continue;
spaces.push({
externalId: `project:${project.id}`,
name: typeof project.name === 'string' && project.name !== '' ? project.name : project.id,
description: 'LongMemory project',
connection: { projectId: project.id },
});
}
return spaces;
}
/** Health = the service answers its storage status endpoint. */
async status(body, signal) {
signal?.throwIfAborted();
const resolved = this.resolve(body);
// No local token short-circuit: the factory owns the sidecar fallback, so
// only the live call can tell whether a token is configured anywhere.
const result = await this.client(resolved).storageStatus();
return result.ok
? { healthy: true }
: { healthy: false, error: result.error.message };
}
/** Live pass-through search — this is the recall path for every turn. */
async search(body, request, signal) {
signal?.throwIfAborted();
const resolved = this.resolve(body);
const limit = Math.min(Math.max(request.limit ?? 10, 1), 100);
const result = await this.client(resolved).search(request.query, limit, resolved.projectId);
if (!result.ok) {
throw new Error(`LongMemory search failed: ${result.error.message}`);
}
return {
results: (result.data.matches ?? [])
.map(insightFromHit)
.filter((item) => item !== undefined),
};
}
/** Browse the space; a query, when given, defers to live search. */
async list(body, request, signal) {
signal?.throwIfAborted();
if (request.query !== undefined && request.query !== '') {
const found = await this.search(body, { query: request.query, limit: request.limit ?? 100 }, signal);
return found.results;
}
const resolved = this.resolve(body);
const limit = Math.min(Math.max(request.limit ?? 100, 1), 200);
const result = await this.client(resolved).list({ limit, project: resolved.projectId });
if (!result.ok) {
throw new Error(`LongMemory list failed: ${result.error.message}`);
}
return (result.data.items ?? [])
.map(insightFromHit)
.filter((item) => item !== undefined);
}
/** Store one memory straight into the cloud store — no local staging. */
async remember(body, request, signal) {
signal?.throwIfAborted();
const resolved = this.resolve(body);
const result = await this.client(resolved).add({
content: request.content,
...(request.tags === undefined ? {} : { tags: request.tags }),
...(resolved.projectId === undefined ? {} : { project: resolved.projectId }),
...(request.category === undefined ? {} : { sector: request.category }),
operationId: `mnemon-${randomUUID()}`,
});
if (!result.ok) {
throw new Error(`LongMemory remember failed: ${result.error.message}`);
}
return {
action: 'stored',
provider: this.id,
summary: 'Stored in LongMemory (live).',
...(result.data.id === undefined ? {} : { id: result.data.id }),
...(result.data.revision === undefined ? {} : { revision: result.data.revision }),
};
}
/** Exact read of one memory by id. */
async get(body, id, signal) {
signal?.throwIfAborted();
const resolved = this.resolve(body);
const result = await this.client(resolved).read(id);
if (!result.ok)
return undefined;
return insightFromHit(result.data);
}
/**
* LongMemory's associations live server-side and this API exposes no
* graph read, so the honest v1 answer is an empty snapshot; the
* descriptor declares the graph capability off to match.
*/
async graph(body, signal) {
signal?.throwIfAborted();
void body;
return { nodes: [], edges: [], generatedAt: new Date().toISOString() };
}
}