dsh-brain/lib/mnemon/driver.js

277 lines
12 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;
}
/**
* Classify a LongMemory write receipt without trusting it.
*
* The service may stage a write (remote_saved:false / state:'pending'), may
* answer with a bare 200 and no usable body, or may return fields of the
* wrong type. An explicit `state` wins over every other hint; a receipt that
* says the write is staged can never be promoted to `stored` by an id or a
* revision. Unknown state values and malformed fields degrade to `unknown`
* instead of throwing or guessing.
*/
export function classifyWriteReceipt(receipt) {
if (receipt === null || typeof receipt !== 'object' || Array.isArray(receipt))
return 'unknown';
const body = receipt;
const state = typeof body.state === 'string' ? body.state.trim().toLowerCase() : '';
if (state !== '') {
if (state === 'pending' || state === 'queued')
return 'pending';
if (state === 'stored' || state === 'saved' || state === 'completed') {
// The explicit state says saved, but a contradictory remote_saved:false
// still means the write is only staged — never report it as stored.
return body.remote_saved === false ? 'pending' : 'stored';
}
return 'unknown';
}
if (typeof body.remote_saved === 'boolean')
return body.remote_saved ? 'stored' : 'pending';
// Older servers answer with just the created id (and sometimes revision);
// that is the only remaining signal that the write reached the store.
if (typeof body.id === 'string' && body.id !== '')
return 'stored';
if (typeof body.revision === 'number' && Number.isFinite(body.revision))
return 'stored';
return 'unknown';
}
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}`);
}
// The write receipt decides what to report — the service may stage the
// write (remote_saved:false) or answer with a bare 200 and no usable
// body, and claiming `stored` then would be a lie the UI repeats.
const receipt = result.data;
const action = classifyWriteReceipt(receipt);
const record = receipt !== null && typeof receipt === 'object' && !Array.isArray(receipt)
? receipt
: {};
const id = typeof record.id === 'string' && record.id !== '' ? record.id : undefined;
const revision = typeof record.revision === 'number' && Number.isFinite(record.revision)
? record.revision
: undefined;
const summary = action === 'stored'
? 'Stored in LongMemory (live).'
: action === 'pending'
? 'Queued by LongMemory; not yet confirmed as saved.'
: 'LongMemory accepted the write but the receipt does not confirm storage; state unknown.';
return {
action,
provider: this.id,
summary,
...(id === undefined ? {} : { id }),
...(revision === undefined ? {} : { 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;
// The read is exact-id, so the service may return a memory from ANY
// project the account can see. A space explicitly bound to one project
// must not leak hits from another, while the account-wide default space
// (no projectId) intentionally reads every project the token can access.
const spaceProject = resolved.projectId;
if (spaceProject !== undefined) {
const hitProject = result.data.project_id;
if (typeof hitProject !== 'string' || hitProject !== spaceProject)
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() };
}
}