dsh-brain/src-client/mnemon.ts

119 lines
6.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Read-only Mnemon data source.
//
// dsh-brain no longer stores memory itself: Mnemon is the single source of
// truth, read through the /dsh-brain/mnemon/* bridge (which forwards Mnemon's
// own RPC envelope {ok,value}). This module normalizes those responses into
// the {ok,total,items} shape the panel already consumes, so the page structure
// and styles stay put — only the data binding moves.
//
// Honesty rules (agreed with the secretary): runtime entries carry no id,
// category, session source or revision. The id falls back to the index; the
// missing fields stay undefined so the UI marks them 「待核实」. Nothing is
// fabricated to make the screen look fuller.
import { request, bodyError } from './api'
import { scopeParams, type BrainScope } from './panel/workspace'
export const MNEMON = {
runtime: '/dsh-brain/mnemon/runtime',
list: '/dsh-brain/mnemon/list',
status: '/dsh-brain/mnemon/status',
search: '/dsh-brain/mnemon/search',
documents: '/dsh-brain/mnemon/documents',
}
/** The bridge keeps Mnemon's {ok:false,error:{code,message}} envelope. */
function envelopeError(result: any, fallback: string): string {
const err = result.body?.error
if (err !== null && typeof err === 'object' && typeof err.message === 'string' && err.message !== '') return err.message
if (err === 'mnemon-project-workspace-required') return '无法确认 Mnemon 项目工作区。'
if (result.status === 503) return 'Mnemon 读服务未接入:当前宿主没有 Mnemon,界面暂不显示记忆。'
return bodyError(result, fallback)
}
export interface NormalizedItem {
id: string
scope: string
content: string
category?: string
tags: string[]
source: string
revision?: number
createdAt?: string
updatedAt?: string
target?: string
importance?: string
mnemon: boolean
}
/** Runtime snapshot → newest-created-first list. No id/category/source exists. */
export function runtimeEntriesToList(value: any): NormalizedItem[] {
const entries: any[] = Array.isArray(value?.entries) ? value.entries : []
const items = entries.map((entry, index): NormalizedItem => ({
id: 'mnemon_rt_' + String(index),
scope: 'global',
content: String(entry?.content ?? ''),
category: undefined,
tags: [],
source: 'mnemon',
revision: undefined,
createdAt: typeof entry?.created_at === 'string' ? entry.created_at : undefined,
updatedAt: typeof entry?.updated_at === 'string' ? entry.updated_at : undefined,
target: typeof entry?.target === 'string' ? entry.target : undefined,
importance: typeof entry?.importance === 'string' ? entry.importance : undefined,
mnemon: true,
}))
items.sort((a, b) => String(b.createdAt ?? '').localeCompare(String(a.createdAt ?? '')))
return items
}
/** Global uses the runtime snapshot; project uses the selected Memory Spaces list. */
export async function mnemonMemories(scope: BrainScope): Promise<{ ok: true; total: number; items: NormalizedItem[]; categoriesAvailable: boolean }> {
if (scope.scope === 'project') {
const params = scopeParams(scope)
params.set('limit', '1000')
const result = await request(MNEMON.list + '?' + params.toString())
if (result.status !== 200 || result.body === null || result.body.ok !== true) throw new Error(envelopeError(result, '读取 Mnemon 项目记忆失败'))
const value = result.body.value ?? {}
const raw: any[] = Array.isArray(value.items) ? value.items : []
const items = raw.map((it, index): NormalizedItem => ({
id: typeof it?.id === 'string' && it.id !== '' ? it.id : 'mnemon_sp_' + String(index),
scope: 'project',
content: String(it?.content ?? ''),
category: typeof it?.category === 'string' ? it.category : undefined,
tags: Array.isArray(it?.tags) ? it.tags.filter((t: unknown): t is string => typeof t === 'string') : [],
source: 'mnemon',
revision: typeof it?.revision === 'number' ? it.revision : undefined,
createdAt: typeof it?.created_at === 'string' ? it.created_at : typeof it?.createdAt === 'string' ? it.createdAt : undefined,
updatedAt: typeof it?.updated_at === 'string' ? it.updated_at : typeof it?.updatedAt === 'string' ? it.updatedAt : undefined,
mnemon: true,
}))
items.sort((a, b) => String(b.createdAt ?? '').localeCompare(String(a.createdAt ?? '')))
const total = typeof value.total === 'number' ? value.total : items.length
return { ok: true, total, items, categoriesAvailable: items.some((it) => it.category !== undefined) }
}
return mnemonRuntimeAll()
}
/** Full runtime list (no paging) for the overview's totals and 7-day trend. */
export async function mnemonRuntimeAll(): Promise<{ ok: true; total: number; items: NormalizedItem[]; categoriesAvailable: false }> {
const result = await request(MNEMON.runtime)
if (result.status !== 200 || result.body === null || result.body.ok !== true) throw new Error(envelopeError(result, '读取 Mnemon 记忆失败'))
const items = runtimeEntriesToList(result.body.value)
return { ok: true, total: items.length, items, categoriesAvailable: false }
}
/** Mnemon status snapshot (storage root, sources, workspace mode). */
export async function mnemonStatus(scope?: BrainScope): Promise<any> {
const query = scope?.scope === 'project' ? '?' + scopeParams(scope).toString() : ''
const result = await request(MNEMON.status + query)
if (result.status !== 200 || result.body === null || result.body.ok !== true) throw new Error(envelopeError(result, '读取 Mnemon 状态失败'))
return result.body.value ?? {}
}
export async function mnemonDocuments(scope: Extract<BrainScope, { scope: 'project' }>): Promise<{ documents: any[] }> {
const result = await request(MNEMON.documents + '?' + scopeParams(scope).toString())
if (result.status !== 200 || result.body === null || result.body.ok !== true) throw new Error(envelopeError(result, '读取 Mnemon 文档失败'))
const value = result.body.value ?? {}
return { documents: Array.isArray(value.items) ? value.items : Array.isArray(value.documents) ? value.documents : [] }
}