// ─── API 客户端(调用织忆 Go API)───────────────────────────────────────────── const API_BASE = "http://localhost:7821"; const API_KEY = "zhiyi-dev-key-2026"; // 运行时配置覆盖(由设置页写入) interface RuntimeConfig { apiUrl?: string; apiKey?: string; namespace?: string; } const cfg: RuntimeConfig = {}; export function getApiBase() { return (cfg.apiUrl || API_BASE).replace(/\/$/, ""); } export function getApiKey() { return cfg.apiKey || API_KEY; } export function setRuntimeConfig(url: string, key: string, ns: string) { cfg.apiUrl = url; cfg.apiKey = key; cfg.namespace = ns; } export function getRuntimeNamespace() { return cfg.namespace || "hermes-main"; } interface ApiOptions { method?: string; body?: unknown; } async function apiCall( path: string, opts: ApiOptions = {} ): Promise { const method = opts.method ?? "GET"; const headers: Record = { "X-API-Key": getApiKey(), "Content-Type": "application/json", }; const init: RequestInit = { method, headers }; if (opts.body !== undefined) { init.body = JSON.stringify(opts.body); } const res = await fetch(`${getApiBase()}${path}`, init); if (!res.ok) { throw new Error(`API ${path} failed: ${res.status} ${res.statusText}`); } const text = await res.text(); if (!text) return {} as T; return JSON.parse(text) as T; } // ─── 数据类型 ──────────────────────────────────────────────────────────────── export interface MemoryRecord { id: string; content: string; category: string; namespace: string; quality_score: number; created_at: string; agent_id?: string; importance?: number; recall_count?: number; tier?: string; } export interface GraphNode { id: string; label: string; category?: string; weight?: number; } export interface GraphEdge { source: string; target: string; relation: string; weight?: number; } export interface GraphNavigateResult { nodes: GraphNode[]; edges: GraphEdge[]; paths: Array<{ source: string; target: string; relation: string }>; } export interface RecallResult { memories: Array<{ id: string; content: string; score: number; category: string; created_at: string }>; } export interface DistillStatus { queue_len: number; daily_used: number; daily_limit: number; batch_size: number; last_distill?: string; } export interface DistillQuota { remaining: number; used: number; limit: number; status: string; } // ─── API 方法 ──────────────────────────────────────────────────────────────── export async function fetchStats() { return apiCall<{ total_memories: number; total_episodes: number; backend: string }>( "/api/v1/stats" ); } export async function fetchMemories(opts: { namespace?: string; limit?: number; offset?: number; category?: string; }): Promise<{ memories: MemoryRecord[]; total: number }> { const params = new URLSearchParams(); const ns = opts.namespace || getRuntimeNamespace(); if (ns) params.set("namespace", ns); if (opts.limit) params.set("limit", String(opts.limit)); if (opts.offset !== undefined) params.set("offset", String(opts.offset)); if (opts.category) params.set("category", opts.category); const qs = params.toString(); return apiCall(`/api/v1/memories?${qs}`); } export async function searchMemories(query: string, namespace?: string) { return apiCall<{ memories: RecallResult["memories"] }>("/api/v1/search/recall", { method: "POST", body: { query, namespace: namespace || getRuntimeNamespace(), top_k: 20 }, }); } export async function fetchNeighbors(entity: string) { return apiCall(`/api/v1/graph/navigate?entity=${encodeURIComponent(entity)}&depth=1`); } export async function fetchGraphExport(namespace?: string, limit = 100) { return apiCall<{ nodes: GraphNode[]; edges: GraphEdge[] }>( `/api/v1/graph/export?namespace=${namespace || getRuntimeNamespace()}&limit=${limit}` ); } export async function fetchDistillStatus(): Promise { return apiCall("/api/v1/distill/status"); } export async function fetchDistillQuota(): Promise { return apiCall("/api/v1/distill/quota"); } export async function fetchPageRank(limit = 30) { return apiCall<{ pagerank: Array<{ entity: string; score: number }>; count: number }>( `/api/v1/graph/pagerank?limit=${limit}` ); } export async function fetchByEntity(entity: string) { return apiCall<{ memories: MemoryRecord[] }>( `/api/v1/memories/by-entity/${encodeURIComponent(entity)}` ); } // ─── 写入记忆 ────────────────────────────────────────────────────────────── export async function writeMemory( content: string, category = "normal", namespace?: string ): Promise<{ id: string }> { return apiCall<{ id: string }>("/api/v1/memories", { method: "POST", body: { content, category, namespace: namespace || getRuntimeNamespace(), source: "obsidian-plugin", }, }); } // ─── 获取所有 category(从记忆列表中提取) ────────────────────────────────── export async function fetchCategories(): Promise { try { const data = await fetchMemories({ limit: 500 }); const cats = new Set(); for (const m of data.memories) { if (m.category) cats.add(m.category); } return Array.from(cats).sort(); } catch { return []; } }