dsh-brain/lib/entries/cloudsync.js

68 lines
2.9 KiB
JavaScript

import { brainKernel, VERSION } from "../kernel.js";
import { buildStatusPayload, legacyAliases } from "../routes.js";
import { createCloudSyncRoutes } from "../cloudsync-routes.js";
export const name = 'dsh-brain-cloudsync';
/** Services required before `apply` runs. */
export const inject = ['webServer'];
/** How often the skill directory is reconciled with the cloud center. */
const SKILL_SYNC_INTERVAL_MS = 15 * 60_000;
/** How often queued reports are retried. */
const RETRY_INTERVAL_MS = 30_000;
/** Register the sub-plugin with the host. */
export function apply(ctx, config) {
const logger = ctx.logger('dsh-brain');
const kernel = brainKernel(config, logger);
kernel.activate('cloudsync');
kernel.logEvent('boot.entry', { bundle: 'cloudsync' });
ctx.effect(() => () => kernel.deactivate('cloudsync'), 'dsh-brain-cloudsync: activation');
// The host's `Events` map is augmented by @deepseek-ai/dsh-session, which a
// third-party bundle cannot rely on; bind the listener through a local shape.
const onEvent = ctx.on;
ctx.effect(() => onEvent('session/event', (session, event) => {
try {
kernel.reporter.handleEvent(session, event);
}
catch (error) {
logger.warn(`turn event handling failed: ${error instanceof Error ? error.message : String(error)}`);
}
}), 'dsh-brain-cloudsync: turn reporting');
ctx.effect(() => {
const timer = setInterval(() => {
if (kernel.store.activityToken() !== '' && kernel.settings().activityEnabled) {
void kernel.reporter.flush().catch((error) => {
logger.warn(`retry flush failed: ${error instanceof Error ? error.message : String(error)}`);
});
}
}, RETRY_INTERVAL_MS);
timer.unref?.();
return () => clearInterval(timer);
}, 'dsh-brain-cloudsync: retry timer');
ctx.effect(() => {
const run = () => {
if (kernel.store.memoryToken() !== '')
void kernel.skillSync.syncOnce().catch(() => { });
};
const first = setTimeout(run, 5_000);
first.unref?.();
const timer = setInterval(run, SKILL_SYNC_INTERVAL_MS);
timer.unref?.();
return () => { clearTimeout(first); clearInterval(timer); };
}, 'dsh-brain-cloudsync: skill sync timer');
const webServer = ctx.webServer;
if (webServer === undefined) {
logger.warn('webServer service unavailable; cloud-sync routes stay disabled');
return;
}
const routes = createCloudSyncRoutes({
store: kernel.store,
client: () => kernel.client,
reporter: kernel.reporter,
sync: kernel.skillSync,
statusView: () => buildStatusPayload(kernel.routeDeps()),
});
routes.push(...legacyAliases(routes));
for (const route of routes) {
ctx.effect(() => webServer.register(route), `dsh-brain-cloudsync: route ${route.path}`);
}
}