dsh-brain/lib/mnemon/read-service.js

63 lines
2.3 KiB
JavaScript

/**
* Read-only bridge to the live Mnemon Host RPC service.
*
* Mnemon registers `mnemonRemote` as a Typert service; its `read` method is the
* same read handler its own `/dsh-mnemon-read` channel serves. dsh-brain reads
* through that service instead of copying Mnemon data: no storage layout is
* touched, and no write/forget endpoint is exposed here.
*
* The service name is resolved lazily from the live Cordis context, so the
* plugin loads and runs when Mnemon is absent; the read routes then answer
* 503 instead of failing plugin activation.
*/
import { resolve } from 'node:path';
/**
* Resolve the live Mnemon read service from a host Context.
*
* `mnemonRemote` is provided by the installed `dsh-mnemon` Host entry. A
* missing service (Mnemon not installed, entry disabled, or a host without the
* web transport) returns undefined; the caller exposes that as a capability
* gap, never as a read of stale data.
*/
export function mnemonReadFromContext(ctx) {
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('mnemonRemote');
if (candidate === null || typeof candidate !== 'object')
return undefined;
const read = candidate.read;
if (typeof read !== 'function')
return undefined;
const service = candidate;
return {
read: (endpoint, payload, signal) => signal === undefined
? service.read(endpoint, payload)
: service.read(endpoint, payload, signal),
workspaceIdForPath: (path) => {
const registry = lookup('workspaceRegistry');
if (registry === undefined || typeof registry.list !== 'function')
return undefined;
let spaces;
try {
spaces = registry.list();
}
catch {
return undefined;
}
const target = resolve(path);
const found = spaces.find((space) => typeof space.id === 'string'
&& typeof space.path === 'string' && resolve(space.path) === target);
return typeof found?.id === 'string' ? found.id : undefined;
},
};
}