61 lines
2.3 KiB
JavaScript
61 lines
2.3 KiB
JavaScript
/**
|
|
* Brain's host bridge shares Mnemon's live read handler across Web and headless
|
|
* sessions. Only the in-process tool bridge can append memory.
|
|
* Service lookup is lazy so plugin activation can occur in either order.
|
|
*/
|
|
import { relative } from 'node:path';
|
|
/**
|
|
* Resolve the bundled host service. Web reads can also use standalone Mnemon.
|
|
*/
|
|
function mnemonServiceFromContext(ctx, allowStandalone) {
|
|
const get = ctx.get;
|
|
if (typeof get !== 'function')
|
|
return undefined;
|
|
const lookup = (name) => {
|
|
try {
|
|
return get.call(ctx, name, false);
|
|
}
|
|
catch {
|
|
return undefined;
|
|
}
|
|
};
|
|
const candidate = lookup('brainMnemonHost') ?? (allowStandalone ? lookup('mnemonRemote') : undefined);
|
|
if (candidate === null || typeof candidate !== 'object')
|
|
return undefined;
|
|
const read = candidate.read;
|
|
if (typeof read !== 'function')
|
|
return undefined;
|
|
const service = candidate;
|
|
const workspaces = () => {
|
|
const registry = lookup('workspaceRegistry');
|
|
try {
|
|
return (registry?.list?.() ?? []).flatMap(space => {
|
|
if (typeof space.id !== 'string' || typeof space.path !== 'string')
|
|
return [];
|
|
const name = typeof space.name === 'string' ? space.name : typeof space.title === 'string' ? space.title : space.path;
|
|
return [{ id: space.id, name, path: space.path }];
|
|
});
|
|
}
|
|
catch {
|
|
return [];
|
|
}
|
|
};
|
|
const bridge = {
|
|
read: (endpoint, payload, signal) => service.read(endpoint, payload, signal),
|
|
workspaceIdForPath: path => workspaces().find(space => relative(space.path, path) === '')?.id,
|
|
};
|
|
return { service, bridge, workspaces };
|
|
}
|
|
export function mnemonReadFromContext(ctx) {
|
|
return mnemonServiceFromContext(ctx, true)?.bridge;
|
|
}
|
|
export function mnemonToolsFromContext(ctx) {
|
|
const resolved = mnemonServiceFromContext(ctx, false);
|
|
if (resolved === undefined)
|
|
return undefined;
|
|
const append = resolved.service.appendBrainMemory?.bind(resolved.service) ?? (async () => ({
|
|
ok: false, error: { code: 'mnemon-unavailable', message: '当前 Mnemon 服务未提供 Brain 写入接口。' },
|
|
}));
|
|
return { ...resolved.bridge, workspaces: resolved.workspaces, append };
|
|
}
|