dsh-brain/lib/local-memory/remote.js

47 lines
2.3 KiB
JavaScript

function hitOf(record) {
return { id: record.id, content: record.content, tags: record.tags, project_id: record.projectId ?? null, primary_sector: record.category, revision: record.revision, created_at: Date.parse(record.createdAt), updated_at: Date.parse(record.updatedAt) };
}
function ok(data) { return { ok: true, status: 200, data }; }
export class LocalMemoryRemote {
manager;
constructor(manager) {
this.manager = manager;
}
run(workspace, job) {
return workspace === undefined ? job() : this.manager.withWorkspace(workspace, job);
}
async search(query, k, project, workspace) {
return this.run(workspace, async () => {
const records = await this.manager.search(query, k, workspace, project);
const matches = records.map(hitOf);
return ok({ matches, total: matches.length, search_mode: 'local' });
});
}
async read(id, workspace) {
return this.run(workspace, async () => {
const record = await this.manager.read(id, workspace);
if (record === undefined)
return { ok: false, error: { status: 404, code: 'memory_not_found', message: '记忆不存在' } };
return ok(hitOf(record));
});
}
async add(input, workspace) {
return this.run(workspace, async () => {
const result = await this.manager.remember({ content: input.content, tags: input.tags, category: input.sector, source: 'memory_tool', operationId: input.operationId, scope: input.project === 'global' ? 'global' : 'project' });
return ok({ id: result.record.id, revision: result.record.revision, state: 'stored', remote_saved: true });
});
}
async list(options = {}, workspace) {
return this.run(workspace, async () => {
const page = await this.manager.list({ limit: options.limit, offset: options.offset }, workspace, options.project);
return ok({ items: page.items.map(hitOf), total: page.total });
});
}
async projects(workspace) {
return this.run(workspace, async () => ok({ projects: await this.manager.projects(workspace) }));
}
async storageStatus(workspace) {
return this.run(workspace, async () => ok(await this.manager.storageStatus(workspace)));
}
}