diff --git a/openclaw-zhiyi-plugin/dist/cli.d.ts b/openclaw-zhiyi-plugin/dist/cli.d.ts new file mode 100644 index 0000000..9c8054d --- /dev/null +++ b/openclaw-zhiyi-plugin/dist/cli.d.ts @@ -0,0 +1,10 @@ +#!/usr/bin/env node +/** + * cli.ts — OpenClaw → ZhiYi migration tool + * + * Usage: + * node dist/cli.js migrate --lance-dir ~/.openclaw/memory-lancedb/memories.lance + * node dist/cli.js status --lance-dir ~/.openclaw/memory-lancedb/memories.lance + * node dist/cli.js test-zhiyi + */ +export {}; diff --git a/openclaw-zhiyi-plugin/dist/cli.js b/openclaw-zhiyi-plugin/dist/cli.js new file mode 100644 index 0000000..9133c22 --- /dev/null +++ b/openclaw-zhiyi-plugin/dist/cli.js @@ -0,0 +1,265 @@ +#!/usr/bin/env node +"use strict"; +/** + * cli.ts — OpenClaw → ZhiYi migration tool + * + * Usage: + * node dist/cli.js migrate --lance-dir ~/.openclaw/memory-lancedb/memories.lance + * node dist/cli.js status --lance-dir ~/.openclaw/memory-lancedb/memories.lance + * node dist/cli.js test-zhiyi + */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const path = __importStar(require("path")); +const os = __importStar(require("os")); +class ZhiYiClient { + baseUrl; + apiKey; + constructor(baseUrl = "http://localhost:7821", apiKey = process.env.ZHIYI_API_KEY || "zhiyi-dev-key-2026") { + this.baseUrl = baseUrl; + this.apiKey = apiKey; + } + async commit(payload) { + const res = await fetch(`${this.baseUrl}/api/v1/commit`, { + method: "POST", + headers: { + "Content-Type": "application/json", + "X-API-Key": this.apiKey, + }, + body: JSON.stringify(payload), + }); + if (!res.ok) { + const body = await res.text(); + throw new Error(`ZhiYi commit failed: ${res.status} ${body}`); + } + return res.json(); + } + async commitBatch(payloads) { + const res = await fetch(`${this.baseUrl}/api/v1/commit/batch`, { + method: "POST", + headers: { + "Content-Type": "application/json", + "X-API-Key": this.apiKey, + }, + body: JSON.stringify(payloads), + }); + if (!res.ok) { + const body = await res.text(); + throw new Error(`ZhiYi batch commit failed: ${res.status} ${body}`); + } + return res.json(); + } + async getStats() { + const res = await fetch(`${this.baseUrl}/api/v1/stats`, { + headers: { "X-API-Key": this.apiKey }, + }); + if (!res.ok) + throw new Error(`Stats failed: ${res.status}`); + return res.json(); + } + async search(query, namespace = "openclaw-main", topK = 5) { + const res = await fetch(`${this.baseUrl}/api/v1/recall?q=${encodeURIComponent(query)}&top_k=${topK}&namespace=${encodeURIComponent(namespace)}`, { headers: { "X-API-Key": this.apiKey } }); + if (!res.ok) + throw new Error(`Search failed: ${res.status}`); + return res.json(); + } +} +// ── LanceDB Reader ─────────────────────────────────────────────────────────── +async function readMemoriesFromLanceDB(lanceDir) { + // Dynamically load @lancedb/lancedb from memory-lancedb-pro's node_modules + const memoryLancedbPath = path.join(os.homedir(), ".openclaw", "workspace", "plugins", "memory-lancedb", "node_modules", "@lancedb", "lancedb"); + // eslint-disable-next-line @typescript-eslint/no-var-requires + const lancedb = require(memoryLancedbPath); + // LanceDB 0.26: use connect() factory, returns Connection + const db = await lancedb.connect(lanceDir); + const table = await db.openTable("memories"); + const allEntries = []; + const BATCH = 500; + while (true) { + // LanceDB 0.26 API: query().limit(n).toArray() returns Promise + const batch = await table.query().limit(BATCH).toArray(); + if (batch.length === 0) + break; + allEntries.push(...batch); + if (batch.length < BATCH) + break; + console.error(` Read ${allEntries.length} entries...`); + } + return allEntries; +} +// ── Entity extraction ──────────────────────────────────────────────────────── +function extractEntities(text) { + const entities = []; + const lower = text.toLowerCase(); + // Capitalized multi-word phrases + const capitalized = text.match(/[A-Z][a-z]+(?:\s+[A-Z][a-z]+)*/g) || []; + entities.push(...capitalized.slice(0, 3)); + // Quoted strings + const quoted = text.match(/"([^"]+)"/g) || []; + entities.push(...quoted.slice(0, 2).map((q) => q.replace(/"/g, ""))); + // Known key topics + const topics = [ + "织忆", "MemoryWeave", "OpenClaw", "Hermes", "ComfyUI", + "牧尘", "小唯", "小红书", "AI", "ChatGPT", "LLM", + ]; + for (const t of topics) { + if (lower.includes(t.toLowerCase())) + entities.push(t); + } + return [...new Set(entities)].slice(0, 5); +} +// ── Commands ───────────────────────────────────────────────────────────────── +async function cmdMigrate(lanceDir, zhiyiUrl, apiKey) { + const zhiyi = new ZhiYiClient(zhiyiUrl, apiKey); + const resolved = lanceDir.replace("~", os.homedir()); + console.error("Reading LanceDB..."); + const entries = await readMemoriesFromLanceDB(resolved); + console.error(`\nTotal entries found: ${entries.length}`); + const valid = entries.filter((e) => e.id !== "__schema__" && e.text.trim().length > 0); + console.error(`Valid entries: ${valid.length}`); + const byCategory = {}; + for (const e of valid) { + byCategory[e.category] = (byCategory[e.category] || 0) + 1; + } + console.error("\nBy category:"); + for (const [cat, count] of Object.entries(byCategory)) { + console.error(` ${cat}: ${count}`); + } + const BATCH = 50; + const committed = []; + console.error(`\nCommitting to ZhiYi (openclaw-main)...`); + for (let i = 0; i < valid.length; i += BATCH) { + const batch = valid.slice(i, i + BATCH); + const payloads = batch.map((entry) => ({ + namespace: "openclaw-main", + content: entry.text, + entities: extractEntities(entry.text), + source: `openclaw:${entry.category}`, + commit_message: `migrated from openclaw:${entry.id} (scope=${entry.scope})`, + })); + try { + const result = await zhiyi.commitBatch(payloads); + committed.push(...result.ids); + console.error(` Batch ${Math.floor(i / BATCH) + 1}: committed ${batch.length}`); + } + catch (err) { + console.error(` Batch ${Math.floor(i / BATCH) + 1}: FAILED — ${err}`); + console.error(" Retrying one by one..."); + for (const p of payloads) { + try { + const r = await zhiyi.commit(p); + committed.push(r.id); + } + catch (e) { + console.error(` Failed: ${p.content.slice(0, 60)}... — ${e}`); + } + } + } + } + console.error(`\nDone: ${committed.length}/${valid.length} committed`); + return { total: valid.length, committed: committed.length }; +} +async function cmdStatus(lanceDir) { + const resolved = lanceDir.replace("~", os.homedir()); + console.error("Reading LanceDB..."); + const entries = await readMemoriesFromLanceDB(resolved); + const valid = entries.filter((e) => e.id !== "__schema__" && e.text.trim().length > 0); + const byCategory = {}; + const byScope = {}; + const importanceBuckets = { high: 0, mid: 0, low: 0 }; + for (const e of valid) { + byCategory[e.category] = (byCategory[e.category] || 0) + 1; + byScope[e.scope] = (byScope[e.scope] || 0) + 1; + if (e.importance >= 7) + importanceBuckets.high++; + else if (e.importance >= 4) + importanceBuckets.mid++; + else + importanceBuckets.low++; + } + console.log(JSON.stringify({ + total_entries: entries.length, + valid_entries: valid.length, + by_category: byCategory, + by_scope: byScope, + importance_distribution: importanceBuckets, + sample_entries: valid.slice(0, 3).map((e) => ({ + id: e.id, + category: e.category, + scope: e.scope, + text_preview: e.text.slice(0, 120) + (e.text.length > 120 ? "..." : ""), + })), + }, null, 2)); +} +async function cmdTestZhiyi(zhiyiUrl, apiKey) { + const zhiyi = new ZhiYiClient(zhiyiUrl, apiKey); + console.error("Testing ZhiYi connection..."); + try { + const stats = await zhiyi.getStats(); + console.log(JSON.stringify({ ok: true, stats })); + } + catch (err) { + console.error(`Connection failed: ${err}`); + process.exit(1); + } +} +// ── CLI ─────────────────────────────────────────────────────────────────────── +const [cmd, ...args] = process.argv.slice(2); +if (cmd === "migrate") { + const lanceDir = args[0] || `${os.homedir()}/.openclaw/memory-lancedb/memories.lance`; + cmdMigrate(lanceDir, process.env.ZHIYI_URL, process.env.ZHIYI_API_KEY).catch((err) => { + console.error(`\nMigration failed: ${err}`); + process.exit(1); + }); +} +else if (cmd === "status") { + const lanceDir = args[0] || `${os.homedir()}/.openclaw/memory-lancedb/memories.lance`; + cmdStatus(lanceDir).catch((err) => { + console.error(`Status failed: ${err}`); + process.exit(1); + }); +} +else if (cmd === "test-zhiyi") { + cmdTestZhiyi(process.env.ZHIYI_URL, process.env.ZHIYI_API_KEY); +} +else { + console.error(`Usage: + node dist/cli.js migrate [--lance-dir PATH] # LanceDB → ZhiYi + node dist/cli.js status [--lance-dir PATH] # LanceDB stats + node dist/cli.js test-zhiyi # test ZhiYi connection + +Env: ZHIYI_URL, ZHIYI_API_KEY`); + process.exit(1); +} diff --git a/openclaw-zhiyi-plugin/dist/client.d.ts b/openclaw-zhiyi-plugin/dist/client.d.ts new file mode 100644 index 0000000..69f3492 --- /dev/null +++ b/openclaw-zhiyi-plugin/dist/client.d.ts @@ -0,0 +1,17 @@ +import type { ZhiYiMemoryConfig, RecallResult, SearchNotesResult, GraphPath } from './types'; +export declare class ZhiYiClient { + private client; + private ns; + constructor(config: ZhiYiMemoryConfig); + health(): Promise; + commit(content: string, category?: string, metadata?: Record): Promise; + batchCommit(items: Array<{ + content: string; + category?: string; + metadata?: Record; + }>): Promise; + recall(query: string, topK?: number): Promise; + searchNotes(entity: string, maxHops?: number, maxNotes?: number): Promise; + navigate(entity: string, maxHops?: number): Promise; + stats(): Promise>; +} diff --git a/openclaw-zhiyi-plugin/dist/client.js b/openclaw-zhiyi-plugin/dist/client.js new file mode 100644 index 0000000..c6cf723 --- /dev/null +++ b/openclaw-zhiyi-plugin/dist/client.js @@ -0,0 +1,95 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ZhiYiClient = void 0; +const axios_1 = __importDefault(require("axios")); +class ZhiYiClient { + client; + ns; + constructor(config) { + this.ns = config.namespace || 'openclaw-main'; + this.client = axios_1.default.create({ + baseURL: config.baseUrl, + timeout: config.timeout || 10000, + headers: { + 'Content-Type': 'application/json', + 'X-API-Key': config.apiKey, + }, + }); + } + async health() { + try { + const r = await this.client.get('/health'); + return r.status === 200; + } + catch { + return false; + } + } + async commit(content, category = 'episodes', metadata) { + try { + const r = await this.client.post('/api/v1/commit', { + content, category, metadata: { ...metadata, namespace: this.ns }, + }); + const d = r.data; + return d.commit_id || d.episode_id || d.distilled_id || d.id || null; + } + catch (e) { + console.error('[ZhiYi] commit:', e.message); + return null; + } + } + async batchCommit(items) { + const ids = []; + for (const item of items) { + const id = await this.commit(item.content, item.category || 'episodes', item.metadata); + if (id) + ids.push(id); + } + return ids; + } + async recall(query, topK = 5) { + try { + const r = await this.client.post('/api/v1/recall', { query, top_k: topK, use_rerank: true }); + return (r.data.results || []).map((x) => ({ + id: x.id || '', content: x.content || x.text || '', score: x.score || 0, category: x.category || '', + })); + } + catch (e) { + console.error('[ZhiYi] recall:', e.message); + return []; + } + } + async searchNotes(entity, maxHops = 2, maxNotes = 5) { + try { + const r = await this.client.get('/api/v1/graph/notes', { params: { entity, max_hops: maxHops, max_notes: maxNotes } }); + return r.data.notes || []; + } + catch (e) { + console.error('[ZhiYi] searchNotes:', e.message); + return []; + } + } + async navigate(entity, maxHops = 2) { + try { + const r = await this.client.post('/api/v1/graph/navigate', { entity, max_hops: maxHops, namespace: this.ns }); + return r.data.paths || []; + } + catch (e) { + console.error('[ZhiYi] navigate:', e.message); + return []; + } + } + async stats() { + try { + const r = await this.client.get('/api/v1/stats'); + return r.data; + } + catch { + return {}; + } + } +} +exports.ZhiYiClient = ZhiYiClient; diff --git a/openclaw-zhiyi-plugin/dist/index.d.ts b/openclaw-zhiyi-plugin/dist/index.d.ts new file mode 100644 index 0000000..5cc4244 --- /dev/null +++ b/openclaw-zhiyi-plugin/dist/index.d.ts @@ -0,0 +1,23 @@ +/** + * memory-zhiyi — ZhiYi MemoryWeave Plugin for OpenClaw + */ +import { ZhiYiClient } from './client'; +import type { ZhiYiMemoryConfig } from './types'; +export declare const pluginManifest: { + id: string; + name: string; + description: string; + kind: "memory"; + version: string; +}; +declare const plugin: { + id: string; + name: string; + description: string; + kind: "memory"; + register(api: any): Promise; + getClient(): ZhiYiClient | null; + getConfig(): ZhiYiMemoryConfig | null; +}; +export default plugin; +export { ZhiYiClient }; diff --git a/openclaw-zhiyi-plugin/dist/index.js b/openclaw-zhiyi-plugin/dist/index.js new file mode 100644 index 0000000..7e8c8a4 --- /dev/null +++ b/openclaw-zhiyi-plugin/dist/index.js @@ -0,0 +1,67 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ZhiYiClient = exports.pluginManifest = void 0; +/** + * memory-zhiyi — ZhiYi MemoryWeave Plugin for OpenClaw + */ +const client_1 = require("./client"); +Object.defineProperty(exports, "ZhiYiClient", { enumerable: true, get: function () { return client_1.ZhiYiClient; } }); +exports.pluginManifest = { + id: 'memory-zhiyi', + name: 'Memory (ZhiYi)', + description: 'ZhiYi MemoryWeave — semantic memory with knowledge graph and Obsidian integration', + kind: 'memory', + version: '0.1.0', +}; +let _client = null; +let _config = null; +function loadConfig(api) { + const raw = api.config?.zhiyi || api.config?.memory_zhiyi || {}; + return { + baseUrl: raw.base_url || process.env.ZHIYI_BASE_URL || 'http://localhost:7821', + apiKey: raw.api_key || process.env.ZHIYI_API_KEY || 'zhiyi-dev-key-2026', + namespace: raw.namespace || 'openclaw-main', + timeout: raw.timeout || 10000, + }; +} +const plugin = { + id: exports.pluginManifest.id, + name: exports.pluginManifest.name, + description: exports.pluginManifest.description, + kind: exports.pluginManifest.kind, + async register(api) { + _config = loadConfig(api); + _client = new client_1.ZhiYiClient(_config); + const ok = await _client.health(); + if (!ok) { + api.logger?.error('[memory-zhiyi] ZhiYi unreachable — check ZHIYI_BASE_URL'); + return; + } + api.logger?.info(`[memory-zhiyi] registered — ns=${_config.namespace}`); + // Hook into OpenClaw memory lifecycle + api.on('memory:recall', async (params) => { + if (!_client) + return []; + return await _client.recall(params.query, params.topK ?? 5); + }); + api.on('memory:commit', async (params) => { + if (!_client) + return null; + return await _client.commit(params.content, params.category ?? 'episodes', params.metadata); + }); + api.on('memory:graphNavigate', async (params) => { + if (!_client) + return []; + return await _client.navigate(params.entity, params.maxHops ?? 2); + }); + api.on('memory:searchNotes', async (params) => { + if (!_client) + return []; + return await _client.searchNotes(params.entity, 2, params.maxNotes ?? 5); + }); + api.logger?.info('[memory-zhiyi] all hooks registered'); + }, + getClient() { return _client; }, + getConfig() { return _config; }, +}; +exports.default = plugin; diff --git a/openclaw-zhiyi-plugin/dist/types.d.ts b/openclaw-zhiyi-plugin/dist/types.d.ts new file mode 100644 index 0000000..0367dfe --- /dev/null +++ b/openclaw-zhiyi-plugin/dist/types.d.ts @@ -0,0 +1,25 @@ +export interface ZhiYiMemoryConfig { + baseUrl: string; + apiKey: string; + namespace: string; + timeout?: number; +} +export interface RecallResult { + id: string; + content: string; + score: number; + category: string; +} +export interface SearchNotesResult { + path: string; + title: string; + snippet: string; + entities: string[]; + score: number; +} +export interface GraphPath { + source: string; + target: string; + relation: string; + weight: number; +} diff --git a/openclaw-zhiyi-plugin/dist/types.js b/openclaw-zhiyi-plugin/dist/types.js new file mode 100644 index 0000000..c8ad2e5 --- /dev/null +++ b/openclaw-zhiyi-plugin/dist/types.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/openclaw-zhiyi-plugin/scripts/migrate_lancedb_to_zhiyi.py b/openclaw-zhiyi-plugin/scripts/migrate_lancedb_to_zhiyi.py new file mode 100644 index 0000000..6304f66 --- /dev/null +++ b/openclaw-zhiyi-plugin/scripts/migrate_lancedb_to_zhiyi.py @@ -0,0 +1,336 @@ +#!/usr/bin/env python3 +""" +migrate_lancedb_to_zhiyi.py + +Python fallback migration script — bypasses the TypeScript LanceDB SDK path bug. + +Uses the memory-lancedb-pro plugin's internal CLI (via Node.js subprocess) to read +all memories, then commits them to ZhiYi (openclaw-main namespace). + +Usage: + python3 migrate_lancedb_to_zhiyi.py status + python3 migrate_lancedb_to_zhiyi.py migrate + python3 migrate_lancedb_to_zhiyi.py test-zhiyi +""" + +import json +import os +import subprocess +import sys +import time +from pathlib import Path + +ZHIYI_URL = os.environ.get("ZHIYI_URL", "http://localhost:7821") +ZHIYI_API_KEY = os.environ.get("ZHIYI_API_KEY", "zhiyi-dev-key-2026") +LANCE_DIR = os.path.join(os.environ["HOME"], ".openclaw", "memory-lancedb", "memories.lance") + +MEMORY_LANCEDB_CLI = os.path.join( + os.environ["HOME"], + ".openclaw", + "workspace", + "plugins", + "memory-lancedb", + "dist", + "cli.js", +) + + +# ── ZhiYi REST client ──────────────────────────────────────────────────────── + +def zhiyi_commit(namespace: str, content: str, entities: list[str], source: str) -> dict: + """Commit a single memory to ZhiYi.""" + payload = { + "namespace": namespace, + "content": content, + "entities": entities, + "source": source, + } + res = subprocess.run( + ["curl", "-s", "-X", "POST", + f"{ZHIYI_URL}/api/v1/commit", + "-H", "Content-Type: application/json", + "-H", f"X-API-Key: {ZHIYI_API_KEY}", + "-d", json.dumps(payload)], + capture_output=True, text=True, timeout=10 + ) + if res.returncode != 0: + raise RuntimeError(f"curl failed: {res.stderr}") + return json.loads(res.stdout) + + +def zhiyi_commit_batch(namespace: str, items: list[dict]) -> dict: + """Batch commit memories to ZhiYi.""" + payload = items + proc = subprocess.run( + ["curl", "-s", "-X", "POST", + f"{ZHIYI_URL}/api/v1/commit/batch", + "-H", "Content-Type: application/json", + "-H", f"X-API-Key: {ZHIYI_API_KEY}", + "-d", json.dumps(payload)], + capture_output=True, text=True, timeout=30 + ) + if proc.returncode != 0: + raise RuntimeError(f"curl failed: {proc.stderr}") + return json.loads(proc.stdout) + + +def zhiyi_stats() -> dict: + """Get ZhiYi stats.""" + res = subprocess.run( + ["curl", "-s", + f"{ZHIYI_URL}/api/v1/stats", + "-H", f"X-API-Key: {ZHIYI_API_KEY}"], + capture_output=True, text=True, timeout=10 + ) + if res.returncode != 0: + raise RuntimeError(f"curl failed: {res.stderr}") + return json.loads(res.stdout) + + +# ── LanceDB reader (via memory-lancedb-pro CLI) ────────────────────────────── + +def extract_entities(text: str) -> list[str]: + """Simple keyword-based entity extraction.""" + entities = [] + lower = text.lower() + + # Capitalized multi-word phrases + import re + capitalized = re.findall(r'[A-Z][a-z]+(?:\s+[A-Z][a-z]+)*', text) + entities.extend(capitalized[:3]) + + # Quoted strings + quoted = re.findall(r'"([^"]+)"', text) + entities.extend(quoted[:2]) + + # Known topics + topics = ["织忆", "MemoryWeave", "OpenClaw", "Hermes", "ComfyUI", + "牧尘", "小唯", "小红书", "AI", "ChatGPT", "LLM"] + for t in topics: + if t.lower() in lower: + entities.append(t) + + return list(dict.fromkeys(entities))[:5] + + +def read_lancedb_memories() -> list[dict]: + """ + Read all memories from OpenClaw's LanceDB using the memory-lancedb-pro CLI. + The CLI already has the proper path resolution and LanceDB integration. + """ + # Use memory-lancedb-pro's CLI to export memories + # The plugin stores memories with category, scope, importance, etc. + # We use a simple node script to query the DB since the plugin's CLI + # doesn't have a raw export command. + # + # Approach: inject a small JS script that uses the plugin's store module + # to read all entries, then print as JSON lines. + + node_script = """ + const path = require('path'); + const os = require('os'); + + // Load the memory-lancedb-pro store module directly + const storePath = path.join(os.homedir(), '.openclaw', 'workspace', 'plugins', 'memory-lancedb', 'dist', 'store.js'); + // We can't require the store directly (it needs OpenClaw plugin context), + // so instead we use @lancedb/lancedb from the plugin's node_modules + const lancedbPath = path.join(os.homedir(), '.openclaw', 'workspace', 'plugins', 'memory-lancedb', 'node_modules', '@lancedb', 'lancedb'); + const lancedb = require(lancedbPath); + + const dbPath = process.argv[2]; + if (!dbPath) { console.error('Usage: node script.js '); process.exit(1); } + + async function main() { + // Try opening the database + let db; + try { + db = await lancedb.connect(dbPath); + } catch (e) { + // Try parent dir (newer LanceDB v2 format) + const parentDir = require('path').dirname(dbPath); + db = await lancedb.connect(parentDir); + } + + const tableNames = await db.tableNames(); + console.error('Tables:', JSON.stringify(tableNames)); + + if (!tableNames.includes('memories')) { + console.error('No memories table found'); + process.exit(0); + } + + const table = await db.openTable('memories'); + const all = []; + const BATCH = 500; + let offset = 0; + + while (true) { + const batch = await table.query().limit(BATCH).offset(offset).toArray(); + if (batch.length === 0) break; + all.push(...batch); + offset += batch.length; + console.error(`Read ${all.length}...`); + if (batch.length < BATCH) break; + } + + // Filter out schema marker + const valid = all.filter(e => e.id !== '__schema__' && e.text && e.text.trim()); + console.error(`Total valid: ${valid.length}`); + console.log(JSON.stringify(valid)); + } + + main().catch(e => { console.error('Error:', e.message); process.exit(1); }); + """ + + script_path = "/tmp/read_lancedb_memories.js" + with open(script_path, "w") as f: + f.write(node_script) + + try: + result = subprocess.run( + ["node", script_path, LANCE_DIR], + capture_output=True, text=True, timeout=30, + env={**os.environ, "NODE_PATH": os.path.join(os.environ["HOME"], ".openclaw", "workspace", "plugins", "memory-lancedb", "node_modules")} + ) + stderr = result.stderr + # Last line with JSON is the output + lines = result.stdout.strip().split("\n") + json_lines = [l for l in lines if l.startswith("[") or l.startswith("{")] + + if not json_lines: + print(f"CLI stderr: {stderr}", file=sys.stderr) + print(f"CLI stdout: {result.stdout[:500]}", file=sys.stderr) + raise RuntimeError("No JSON output from LanceDB reader") + + memories = json.loads(json_lines[-1]) + return memories + finally: + os.unlink(script_path) + + +def cmd_test_zhiyi(): + print("Testing ZhiYi connection...", file=sys.stderr) + stats = zhiyi_stats() + print(json.dumps({"ok": True, "stats": stats}, indent=2)) + + +def cmd_status(): + print("Reading LanceDB via memory-lancedb-pro plugin...", file=sys.stderr) + memories = read_lancedb_memories() + + by_cat: dict = {} + by_scope: dict = {} + imp = {"high": 0, "mid": 0, "low": 0} + + for m in memories: + cat = m.get("category", "unknown") + scope = m.get("scope", "unknown") + importance = m.get("importance", 0) + + by_cat[cat] = by_cat.get(cat, 0) + 1 + by_scope[scope] = by_scope.get(scope, 0) + 1 + + if importance >= 7: + imp["high"] += 1 + elif importance >= 4: + imp["mid"] += 1 + else: + imp["low"] += 1 + + result = { + "total": len(memories), + "by_category": by_cat, + "by_scope": by_scope, + "importance_distribution": imp, + "sample": [ + { + "id": m["id"], + "category": m.get("category"), + "scope": m.get("scope"), + "importance": m.get("importance"), + "text_preview": m.get("text", "")[:120], + } + for m in memories[:3] + ], + } + + print(json.dumps(result, indent=2)) + + +def cmd_migrate(): + print("Reading LanceDB...", file=sys.stderr) + memories = read_lancedb_memories() + print(f"Found {len(memories)} valid entries", file=sys.stderr) + + # Show category breakdown + by_cat: dict = {} + for m in memories: + cat = m.get("category", "unknown") + by_cat[cat] = by_cat.get(cat, 0) + 1 + print(f"By category: {by_cat}", file=sys.stderr) + + BATCH = 50 + committed = 0 + failed = 0 + + print(f"Committing to ZhiYi (openclaw-main)...", file=sys.stderr) + + for i in range(0, len(memories), BATCH): + batch = memories[i:i + BATCH] + items = [ + { + "namespace": "openclaw-main", + "content": m["text"], + "entities": extract_entities(m["text"]), + "source": f"openclaw:{m.get('category', 'unknown')}", + "commit_message": f"migrated from openclaw:{m['id']} (scope={m.get('scope', '?')})", + } + for m in batch + ] + + try: + result = zhiyi_commit_batch("openclaw-main", items) + ids = result.get("ids", []) + committed += len(ids) + print(f" Batch {i // BATCH + 1}: {len(ids)} committed", file=sys.stderr) + except Exception as e: + print(f" Batch {i // BATCH + 1}: FAILED — {e}", file=sys.stderr) + print(" Falling back to individual commits...", file=sys.stderr) + for item in items: + try: + r = zhiyi_commit("openclaw-main", item["content"], item["entities"], item["source"]) + committed += 1 + except Exception as e: + print(f" Failed: {item['content'][:60]}... — {e}", file=sys.stderr) + failed += 1 + + time.sleep(0.1) # Rate limit + + print(f"\nMigration complete: {committed}/{len(memories)} committed", file=sys.stderr) + if failed: + print(f" {failed} failed", file=sys.stderr) + + return committed + + +if __name__ == "__main__": + cmd = sys.argv[1] if len(sys.argv) > 1 else "help" + + if cmd == "test-zhiyi": + cmd_test_zhiyi() + elif cmd == "status": + cmd_status() + elif cmd == "migrate": + cmd_migrate() + else: + print(f"""Usage: python3 migrate_lancedb_to_zhiyi.py + +Commands: + test-zhiyi — test ZhiYi connection + status — show LanceDB memory stats + migrate — migrate all memories to ZhiYi (openclaw-main namespace) + +Environment: + ZHIYI_URL ZhiYi base URL (default: http://localhost:7821) + ZHIYI_API_KEY API key (default: zhiyi-dev-key-2026) +""") \ No newline at end of file diff --git a/openclaw-zhiyi-plugin/src/cli.ts b/openclaw-zhiyi-plugin/src/cli.ts index 7063107..577256b 100644 --- a/openclaw-zhiyi-plugin/src/cli.ts +++ b/openclaw-zhiyi-plugin/src/cli.ts @@ -1,47 +1,298 @@ #!/usr/bin/env node /** - * CLI: migrate-lancedb-to-zhiyi - * - * Reads OpenClaw LanceDB data and commits to ZhiYi openclaw-main namespace. - * + * cli.ts — OpenClaw → ZhiYi migration tool + * * Usage: - * npx ts-node src/cli.ts - * ZHIYI_BASE_URL=http://localhost:7821 ZHIYI_API_KEY=xxx npx ts-node src/cli.ts + * node dist/cli.js migrate --lance-dir ~/.openclaw/memory-lancedb/memories.lance + * node dist/cli.js status --lance-dir ~/.openclaw/memory-lancedb/memories.lance + * node dist/cli.js test-zhiyi */ -import { ZhiYiClient } from './client'; -import * as path from 'path'; -import * as fs from 'fs'; +import * as path from "path"; +import * as os from "os"; -const BASE_URL = process.env.ZHIYI_BASE_URL || 'http://localhost:7821'; -const API_KEY = process.env.ZHIYI_API_KEY || 'zhiyi-dev-key-2026'; -const NAMESPACE = process.env.OC_NAMESPACE || 'openclaw-main'; -const LANCEDB_PATH = path.join(process.env.HOME || '/home/muc', '.openclaw/memory-lancedb'); +// ── Types ─────────────────────────────────────────────────────────────────── -async function main() { - console.log(`[migrate] ZhiYi: ${BASE_URL}`); - console.log(`[migrate] Namespace: ${NAMESPACE}`); - console.log(`[migrate] LanceDB path: ${LANCEDB_PATH}`); - - const client = new ZhiYiClient({ baseUrl: BASE_URL, apiKey: API_KEY, namespace: NAMESPACE }); - - const ok = await client.health(); - if (!ok) { console.error('[migrate] ERROR: ZhiYi unreachable'); process.exit(1); } - - // TODO: OpenClaw LanceDB is a separate store - // For now, guide the user: - console.log('[migrate]'); - console.log('[migrate] LanceDB must be read from OpenClaw workspace.'); - console.log('[migrate] The LanceDB data lives at: ~/.openclaw/memory-lancedb/'); - console.log('[migrate] This migration requires OpenClaw to be running.'); - console.log('[migrate]'); - console.log('[migrate] Manual migration steps:'); - console.log('[migrate] 1. OpenClaw LanceDB stores episodes in ~/.openclaw/memory-lancedb/'); - console.log('[migrate] 2. Export: use OpenClaw CLI or read LanceDB directly'); - console.log('[migrate] 3. Import: call client.batchCommit() with exported data'); - console.log('[migrate] 4. Switch provider: set memory.provider: zhiyi in OpenClaw config'); - console.log('[migrate]'); - console.log('[migrate] TODO: implement LanceDB reader once OpenClaw config is available'); +interface MemoryEntry { + id: string; + text: string; + vector: number[]; + category: "preference" | "fact" | "decision" | "entity" | "other" | "reflection"; + scope: string; + importance: number; + timestamp: number; + metadata?: string; } -main().catch(console.error); \ No newline at end of file +// ── ZhiYi Client ───────────────────────────────────────────────────────────── + +interface ZhiYiCommitPayload { + namespace?: string; + content: string; + entities?: string[]; + source?: string; + commit_message?: string; +} + +class ZhiYiClient { + baseUrl: string; + apiKey: string; + + constructor( + baseUrl = "http://localhost:7821", + apiKey = process.env.ZHIYI_API_KEY || "zhiyi-dev-key-2026" + ) { + this.baseUrl = baseUrl; + this.apiKey = apiKey; + } + + async commit(payload: ZhiYiCommitPayload): Promise<{ id: string }> { + const res = await fetch(`${this.baseUrl}/api/v1/commit`, { + method: "POST", + headers: { + "Content-Type": "application/json", + "X-API-Key": this.apiKey, + }, + body: JSON.stringify(payload), + }); + if (!res.ok) { + const body = await res.text(); + throw new Error(`ZhiYi commit failed: ${res.status} ${body}`); + } + return res.json(); + } + + async commitBatch(payloads: ZhiYiCommitPayload[]): Promise<{ ids: string[] }> { + const res = await fetch(`${this.baseUrl}/api/v1/commit/batch`, { + method: "POST", + headers: { + "Content-Type": "application/json", + "X-API-Key": this.apiKey, + }, + body: JSON.stringify(payloads), + }); + if (!res.ok) { + const body = await res.text(); + throw new Error(`ZhiYi batch commit failed: ${res.status} ${body}`); + } + return res.json(); + } + + async getStats(): Promise<{ total: number; namespaces: Record }> { + const res = await fetch(`${this.baseUrl}/api/v1/stats`, { + headers: { "X-API-Key": this.apiKey }, + }); + if (!res.ok) throw new Error(`Stats failed: ${res.status}`); + return res.json(); + } + + async search(query: string, namespace = "openclaw-main", topK = 5) { + const res = await fetch( + `${this.baseUrl}/api/v1/recall?q=${encodeURIComponent(query)}&top_k=${topK}&namespace=${encodeURIComponent(namespace)}`, + { headers: { "X-API-Key": this.apiKey } } + ); + if (!res.ok) throw new Error(`Search failed: ${res.status}`); + return res.json(); + } +} + +// ── LanceDB Reader ─────────────────────────────────────────────────────────── + +async function readMemoriesFromLanceDB(lanceDir: string): Promise { + // Dynamically load @lancedb/lancedb from memory-lancedb-pro's node_modules + const memoryLancedbPath = path.join( + os.homedir(), + ".openclaw", + "workspace", + "plugins", + "memory-lancedb", + "node_modules", + "@lancedb", + "lancedb" + ); + // eslint-disable-next-line @typescript-eslint/no-var-requires + const lancedb: any = require(memoryLancedbPath); + + // LanceDB 0.26: use connect() factory, returns Connection + const db: any = await lancedb.connect(lanceDir); + const table: any = await db.openTable("memories"); + + const allEntries: MemoryEntry[] = []; + const BATCH = 500; + + while (true) { + // LanceDB 0.26 API: query().limit(n).toArray() returns Promise + const batch: MemoryEntry[] = await table.query().limit(BATCH).toArray(); + if (batch.length === 0) break; + allEntries.push(...batch); + if (batch.length < BATCH) break; + console.error(` Read ${allEntries.length} entries...`); + } + + return allEntries; +} + +// ── Entity extraction ──────────────────────────────────────────────────────── + +function extractEntities(text: string): string[] { + const entities: string[] = []; + const lower = text.toLowerCase(); + + // Capitalized multi-word phrases + const capitalized = text.match(/[A-Z][a-z]+(?:\s+[A-Z][a-z]+)*/g) || []; + entities.push(...capitalized.slice(0, 3)); + + // Quoted strings + const quoted = text.match(/"([^"]+)"/g) || []; + entities.push(...quoted.slice(0, 2).map((q) => q.replace(/"/g, ""))); + + // Known key topics + const topics = [ + "织忆", "MemoryWeave", "OpenClaw", "Hermes", "ComfyUI", + "牧尘", "小唯", "小红书", "AI", "ChatGPT", "LLM", + ]; + for (const t of topics) { + if (lower.includes(t.toLowerCase())) entities.push(t); + } + + return [...new Set(entities)].slice(0, 5); +} + +// ── Commands ───────────────────────────────────────────────────────────────── + +async function cmdMigrate(lanceDir: string, zhiyiUrl?: string, apiKey?: string) { + const zhiyi = new ZhiYiClient(zhiyiUrl, apiKey); + const resolved = lanceDir.replace("~", os.homedir()); + + console.error("Reading LanceDB..."); + const entries = await readMemoriesFromLanceDB(resolved); + console.error(`\nTotal entries found: ${entries.length}`); + + const valid = entries.filter((e) => e.id !== "__schema__" && e.text.trim().length > 0); + console.error(`Valid entries: ${valid.length}`); + + const byCategory: Record = {}; + for (const e of valid) { + byCategory[e.category] = (byCategory[e.category] || 0) + 1; + } + console.error("\nBy category:"); + for (const [cat, count] of Object.entries(byCategory)) { + console.error(` ${cat}: ${count}`); + } + + const BATCH = 50; + const committed: string[] = []; + + console.error(`\nCommitting to ZhiYi (openclaw-main)...`); + + for (let i = 0; i < valid.length; i += BATCH) { + const batch = valid.slice(i, i + BATCH); + const payloads: ZhiYiCommitPayload[] = batch.map((entry) => ({ + namespace: "openclaw-main", + content: entry.text, + entities: extractEntities(entry.text), + source: `openclaw:${entry.category}`, + commit_message: `migrated from openclaw:${entry.id} (scope=${entry.scope})`, + })); + + try { + const result = await zhiyi.commitBatch(payloads); + committed.push(...result.ids); + console.error(` Batch ${Math.floor(i / BATCH) + 1}: committed ${batch.length}`); + } catch (err) { + console.error(` Batch ${Math.floor(i / BATCH) + 1}: FAILED — ${err}`); + console.error(" Retrying one by one..."); + for (const p of payloads) { + try { + const r = await zhiyi.commit(p); + committed.push(r.id); + } catch (e) { + console.error(` Failed: ${p.content.slice(0, 60)}... — ${e}`); + } + } + } + } + + console.error(`\nDone: ${committed.length}/${valid.length} committed`); + return { total: valid.length, committed: committed.length }; +} + +async function cmdStatus(lanceDir: string) { + const resolved = lanceDir.replace("~", os.homedir()); + + console.error("Reading LanceDB..."); + const entries = await readMemoriesFromLanceDB(resolved); + const valid = entries.filter((e) => e.id !== "__schema__" && e.text.trim().length > 0); + + const byCategory: Record = {}; + const byScope: Record = {}; + const importanceBuckets = { high: 0, mid: 0, low: 0 }; + + for (const e of valid) { + byCategory[e.category] = (byCategory[e.category] || 0) + 1; + byScope[e.scope] = (byScope[e.scope] || 0) + 1; + if (e.importance >= 7) importanceBuckets.high++; + else if (e.importance >= 4) importanceBuckets.mid++; + else importanceBuckets.low++; + } + + console.log( + JSON.stringify( + { + total_entries: entries.length, + valid_entries: valid.length, + by_category: byCategory, + by_scope: byScope, + importance_distribution: importanceBuckets, + sample_entries: valid.slice(0, 3).map((e) => ({ + id: e.id, + category: e.category, + scope: e.scope, + text_preview: e.text.slice(0, 120) + (e.text.length > 120 ? "..." : ""), + })), + }, + null, + 2 + ) + ); +} + +async function cmdTestZhiyi(zhiyiUrl?: string, apiKey?: string) { + const zhiyi = new ZhiYiClient(zhiyiUrl, apiKey); + console.error("Testing ZhiYi connection..."); + try { + const stats = await zhiyi.getStats(); + console.log(JSON.stringify({ ok: true, stats })); + } catch (err) { + console.error(`Connection failed: ${err}`); + process.exit(1); + } +} + +// ── CLI ─────────────────────────────────────────────────────────────────────── + +const [cmd, ...args] = process.argv.slice(2); + +if (cmd === "migrate") { + const lanceDir = args[0] || `${os.homedir()}/.openclaw/memory-lancedb/memories.lance`; + cmdMigrate(lanceDir, process.env.ZHIYI_URL, process.env.ZHIYI_API_KEY).catch((err) => { + console.error(`\nMigration failed: ${err}`); + process.exit(1); + }); +} else if (cmd === "status") { + const lanceDir = args[0] || `${os.homedir()}/.openclaw/memory-lancedb/memories.lance`; + cmdStatus(lanceDir).catch((err) => { + console.error(`Status failed: ${err}`); + process.exit(1); + }); +} else if (cmd === "test-zhiyi") { + cmdTestZhiyi(process.env.ZHIYI_URL, process.env.ZHIYI_API_KEY); +} else { + console.error(`Usage: + node dist/cli.js migrate [--lance-dir PATH] # LanceDB → ZhiYi + node dist/cli.js status [--lance-dir PATH] # LanceDB stats + node dist/cli.js test-zhiyi # test ZhiYi connection + +Env: ZHIYI_URL, ZHIYI_API_KEY`); + process.exit(1); +} \ No newline at end of file diff --git a/openclaw-zhiyi-plugin/tsconfig.json b/openclaw-zhiyi-plugin/tsconfig.json index b18c36c..2f44183 100644 --- a/openclaw-zhiyi-plugin/tsconfig.json +++ b/openclaw-zhiyi-plugin/tsconfig.json @@ -7,7 +7,8 @@ "declaration": true, "strict": true, "esModuleInterop": true, - "skipLibCheck": true + "skipLibCheck": true, + "types": ["node"] }, "include": ["src/**/*"] } \ No newline at end of file