201 lines
10 KiB
JavaScript
201 lines
10 KiB
JavaScript
import { createHash } from 'node:crypto';
|
|
const PROJECT_LIST_LIMIT = 1000;
|
|
const CATEGORY_BY_SECTOR = {
|
|
semantic: 'fact',
|
|
episodic: 'context',
|
|
procedural: 'general',
|
|
emotional: 'general',
|
|
reflective: 'insight',
|
|
};
|
|
function row(value) {
|
|
if (value === null || typeof value !== 'object' || Array.isArray(value))
|
|
throw new Error('Mnemon 返回了意外的结果格式。');
|
|
return value;
|
|
}
|
|
function rows(value) {
|
|
if (!Array.isArray(value))
|
|
throw new Error('Mnemon 返回了意外的条目列表格式。');
|
|
return value.map(row);
|
|
}
|
|
function text(value) {
|
|
return typeof value === 'string' && value !== '' ? value : undefined;
|
|
}
|
|
function time(value) {
|
|
const timestamp = typeof value === 'string' ? Date.parse(value) : value;
|
|
return typeof timestamp === 'number' && Number.isFinite(timestamp) ? timestamp : undefined;
|
|
}
|
|
function rpcValue(result) {
|
|
if (!result.ok)
|
|
throw new Error(result.error.message ?? result.error.code ?? 'Mnemon 请求失败。');
|
|
return result.value;
|
|
}
|
|
function failure(status, code, message) {
|
|
return { ok: false, error: { status, code, message } };
|
|
}
|
|
function runtimeId(entry) {
|
|
const identity = JSON.stringify([entry.target, entry.created_at, entry.content]);
|
|
return 'mnemon-rt:' + createHash('sha256').update(identity).digest('hex');
|
|
}
|
|
function projectId(workspaceId, memoryBodyId, id) {
|
|
return 'mnemon-sp:' + Buffer.from(JSON.stringify([workspaceId, memoryBodyId, id])).toString('base64url');
|
|
}
|
|
function decodeProjectId(id) {
|
|
if (!/^mnemon-sp:[A-Za-z0-9_-]{1,16000}$/.test(id))
|
|
return undefined;
|
|
try {
|
|
const decoded = JSON.parse(Buffer.from(id.slice(10), 'base64url').toString('utf8'));
|
|
if (!Array.isArray(decoded) || decoded.length !== 3 || !decoded.every(value => typeof value === 'string' && value !== ''))
|
|
return undefined;
|
|
const [workspaceId, memoryBodyId, memoryId] = decoded;
|
|
if (id !== projectId(workspaceId, memoryBodyId, memoryId))
|
|
return undefined;
|
|
return { workspaceId, memoryBodyId, id: memoryId };
|
|
}
|
|
catch {
|
|
return undefined;
|
|
}
|
|
}
|
|
function runtimeHit(entry) {
|
|
const content = text(entry.content);
|
|
if (content === undefined)
|
|
throw new Error('Mnemon Runtime 条目缺少正文。');
|
|
const created = time(entry.created_at);
|
|
const updated = time(entry.updated_at);
|
|
return {
|
|
id: runtimeId(entry), content, project_id: null,
|
|
...(created === undefined ? {} : { created_at: created }),
|
|
...(updated === undefined ? {} : { updated_at: updated }),
|
|
...(text(entry.target) === undefined ? {} : { target: entry.target }),
|
|
};
|
|
}
|
|
function projectHit(entry, workspaceId) {
|
|
const id = text(entry.id);
|
|
const memoryBodyId = text(entry.memoryBodyId);
|
|
const content = text(entry.content);
|
|
if (id === undefined || memoryBodyId === undefined || content === undefined)
|
|
throw new Error('Mnemon 项目条目缺少可读取的标识或正文。');
|
|
const created = time(entry.created_at ?? entry.createdAt);
|
|
const updated = time(entry.updated_at ?? entry.updatedAt);
|
|
return {
|
|
id: projectId(workspaceId, memoryBodyId, id), content, project_id: workspaceId,
|
|
tags: Array.isArray(entry.tags) ? entry.tags.filter((tag) => typeof tag === 'string') : [],
|
|
...(created === undefined ? {} : { created_at: created }),
|
|
...(updated === undefined ? {} : { updated_at: updated }),
|
|
...(text(entry.category) === undefined ? {} : { category: entry.category }),
|
|
};
|
|
}
|
|
function newestFirst(hits) {
|
|
return hits.sort((left, right) => (right.created_at ?? 0) - (left.created_at ?? 0) || (left.id ?? '').localeCompare(right.id ?? ''));
|
|
}
|
|
function matchingWorkspace(bridge, project) {
|
|
if (!bridge.workspaces().some(workspace => workspace.id === project))
|
|
throw new Error('找不到该 DSH 工作区,请先用 memory_projects 查找项目 ID。');
|
|
return project;
|
|
}
|
|
async function runtimeHits(bridge) {
|
|
const snapshot = row(rpcValue(await bridge.read('runtime-memory', {})));
|
|
return newestFirst(rows(snapshot.entries).map(runtimeHit));
|
|
}
|
|
async function writableSpace(bridge, workspaceId) {
|
|
const directory = row(rpcValue(await bridge.read('body-directory', { workspaceId })));
|
|
const spaces = rows(directory.items).filter(space => {
|
|
const provider = row(space.provider);
|
|
return text(space.id) !== undefined && space.active === true && space.providerEnabled !== false
|
|
&& row(provider.capabilities).remember === true;
|
|
});
|
|
const defaults = spaces.filter(space => space.mnemonDefault === true);
|
|
const candidates = defaults.length > 0 ? defaults : spaces;
|
|
const selected = candidates.length === 1 ? text(candidates[0]?.id) : undefined;
|
|
if (selected === undefined)
|
|
throw new Error('该工作区没有唯一可写的 Mnemon 记忆空间。请在 Mnemon 中配置默认空间。');
|
|
return selected;
|
|
}
|
|
/** Use the same live Mnemon sources as Brain's global and project views. */
|
|
export function createMnemonMemoryRemote(resolveBridge) {
|
|
async function invoke(operation) {
|
|
try {
|
|
const bridge = resolveBridge();
|
|
if (bridge === undefined)
|
|
return failure(503, 'mnemon_unavailable', '当前宿主没有可用的 Mnemon 服务。');
|
|
return await operation(bridge);
|
|
}
|
|
catch (error) {
|
|
return failure(502, 'mnemon_error', error instanceof Error ? error.message : String(error));
|
|
}
|
|
}
|
|
return {
|
|
search: (query, k, project) => invoke(async (bridge) => {
|
|
if (project === undefined) {
|
|
const needle = query.toLocaleLowerCase();
|
|
const matched = (await runtimeHits(bridge)).filter(hit => hit.content?.toLocaleLowerCase().includes(needle));
|
|
return { ok: true, status: 200, data: { matches: matched.slice(0, k), total: matched.length, search_mode: 'keyword' } };
|
|
}
|
|
const workspaceId = matchingWorkspace(bridge, project);
|
|
const result = row(rpcValue(await bridge.read('search', { workspaceId, query, mode: 'keyword', limit: k })));
|
|
const matches = rows(result.results).map(entry => projectHit(entry, workspaceId));
|
|
return { ok: true, status: 200, data: { matches, total: matches.length, search_mode: text(result.mode) ?? 'keyword' } };
|
|
}),
|
|
read: id => invoke(async (bridge) => {
|
|
const missing = () => failure(404, 'mnemon_memory_not_found', '没有找到该 Mnemon 记忆。');
|
|
if (/^mnemon-rt:[a-f0-9]{64}$/.test(id)) {
|
|
const matches = (await runtimeHits(bridge)).filter(hit => hit.id === id);
|
|
if (matches.length > 1)
|
|
return failure(409, 'mnemon_memory_ambiguous', '有多条 Mnemon Runtime 条目匹配此 ID。');
|
|
return matches[0] === undefined ? missing() : { ok: true, status: 200, data: matches[0] };
|
|
}
|
|
const target = decodeProjectId(id);
|
|
if (target === undefined)
|
|
return missing();
|
|
matchingWorkspace(bridge, target.workspaceId);
|
|
const result = rpcValue(await bridge.read('memory-exact', target));
|
|
if (result === null)
|
|
return missing();
|
|
const hit = projectHit(row(result), target.workspaceId);
|
|
if (hit.id !== id)
|
|
return missing();
|
|
return { ok: true, status: 200, data: hit };
|
|
}),
|
|
add: input => invoke(async (bridge) => {
|
|
const { content, operationId, project, tags, sector } = input;
|
|
if (project === undefined) {
|
|
if ((tags?.length ?? 0) !== 0 || sector !== undefined)
|
|
return failure(400, 'mnemon_runtime_metadata_unsupported', '全局 Mnemon Runtime 条目不支持标签或分类。请省略 tags 和 sector。');
|
|
const result = row(rpcValue(await bridge.append('runtime-memory', { action: 'add', target: 'memory', content, operationId })));
|
|
if (result.success !== true || text(result.added) === undefined)
|
|
throw new Error('Mnemon 没有确认保存该 Runtime 条目。');
|
|
const matches = (await runtimeHits(bridge)).filter(hit => hit.target === 'memory' && hit.content === result.added);
|
|
const id = matches.length === 1 ? matches[0]?.id : undefined;
|
|
if (id === undefined)
|
|
throw new Error('Mnemon 返回了保存回执,但 Runtime 中无法唯一定位该条目。');
|
|
return { ok: true, status: 200, data: { id, operation_id: operationId, state: 'saved' } };
|
|
}
|
|
const workspaceId = matchingWorkspace(bridge, project);
|
|
const memoryBodyId = await writableSpace(bridge, workspaceId);
|
|
const category = sector === undefined ? undefined : CATEGORY_BY_SECTOR[sector];
|
|
const result = row(rpcValue(await bridge.append('remember', { workspaceId, memoryBodyId, content, tags, category, operationId })));
|
|
const id = text(result.id);
|
|
if (id === undefined || result.memoryBodyId !== memoryBodyId || result.committed !== true) {
|
|
throw new Error('Mnemon 没有返回可验证的项目记忆保存回执。');
|
|
}
|
|
return { ok: true, status: 200, data: { id: projectId(workspaceId, memoryBodyId, id), operation_id: operationId, state: 'saved' } };
|
|
}),
|
|
list: (options = {}) => invoke(async (bridge) => {
|
|
const { offset = 0, limit = 20, project } = options;
|
|
if (project === undefined) {
|
|
const hits = await runtimeHits(bridge);
|
|
return { ok: true, status: 200, data: { items: hits.slice(offset, offset + limit), total: hits.length } };
|
|
}
|
|
const workspaceId = matchingWorkspace(bridge, project);
|
|
const result = row(rpcValue(await bridge.read('list', { workspaceId, limit: PROJECT_LIST_LIMIT })));
|
|
const hits = newestFirst(rows(result.items).map(entry => projectHit(entry, workspaceId)));
|
|
return { ok: true, status: 200, data: { items: hits.slice(offset, offset + limit), total: typeof result.total === 'number' ? result.total : hits.length } };
|
|
}),
|
|
projects: () => invoke(async (bridge) => ({
|
|
ok: true, status: 200, data: { projects: bridge.workspaces().map(({ id, name }) => ({ id, name })) },
|
|
})),
|
|
storageStatus: () => invoke(async (bridge) => ({
|
|
ok: true, status: 200, data: row(rpcValue(await bridge.read('status', {}))),
|
|
})),
|
|
};
|
|
}
|