"""Turso(libSQL)資料庫:直接走 Hrana-over-HTTP(/v2/pipeline),不需要原生驅動。""" import json import time import uuid import httpx from . import config def now_ms() -> int: return int(time.time() * 1000) class Turso: def __init__(self, url: str, token: str): url = (url or "").strip() if url.startswith("libsql://"): url = "https://" + url[len("libsql://"):] self.endpoint = url.rstrip("/") + "/v2/pipeline" self.headers = {"Authorization": f"Bearer {token}"} self.client = httpx.AsyncClient(timeout=httpx.Timeout(30, connect=10)) @staticmethod def _arg(v): if v is None: return {"type": "null"} if isinstance(v, bool): return {"type": "integer", "value": str(int(v))} if isinstance(v, int): return {"type": "integer", "value": str(v)} if isinstance(v, float): return {"type": "float", "value": v} return {"type": "text", "value": str(v)} @staticmethod def _val(v): t = v.get("type") if t == "null": return None if t == "integer": return int(v["value"]) if t == "float": return float(v["value"]) if t == "blob": return v.get("base64") return v.get("value") async def batch(self, stmts: list[tuple[str, list | None]]) -> list[dict]: reqs = [ {"type": "execute", "stmt": {"sql": sql, "args": [self._arg(a) for a in (args or [])]}} for sql, args in stmts ] reqs.append({"type": "close"}) r = await self.client.post(self.endpoint, headers=self.headers, json={"requests": reqs}) if r.status_code >= 400: raise RuntimeError(f"Turso HTTP {r.status_code}: {r.text[:300]}") out = [] for res in r.json()["results"][:-1]: if res.get("type") == "error": raise RuntimeError(f"Turso SQL 錯誤: {res['error'].get('message')}") result = res["response"]["result"] cols = [c.get("name") for c in result.get("cols", [])] rows = [{c: self._val(v) for c, v in zip(cols, row)} for row in result.get("rows", [])] rid = result.get("last_insert_rowid") out.append({ "rows": rows, "last_insert_rowid": int(rid) if rid is not None else None, "affected": result.get("affected_row_count", 0), }) return out async def execute(self, sql: str, args: list | None = None) -> dict: return (await self.batch([(sql, args)]))[0] async def close(self): await self.client.aclose() db = Turso(config.TURSO_DATABASE_URL, config.TURSO_AUTH_TOKEN) SCHEMA = [ """CREATE TABLE IF NOT EXISTS conversations ( id TEXT PRIMARY KEY, title TEXT, created_at INTEGER, updated_at INTEGER)""", """CREATE TABLE IF NOT EXISTS messages ( id INTEGER PRIMARY KEY AUTOINCREMENT, conversation_id TEXT NOT NULL, role TEXT NOT NULL, content TEXT, tool_calls TEXT, tool_call_id TEXT, name TEXT, created_at INTEGER)""", "CREATE INDEX IF NOT EXISTS idx_messages_conv ON messages(conversation_id, id)", """CREATE TABLE IF NOT EXISTS memories ( id INTEGER PRIMARY KEY AUTOINCREMENT, content TEXT NOT NULL, tags TEXT, created_at INTEGER)""", "CREATE TABLE IF NOT EXISTS settings (key TEXT PRIMARY KEY, value TEXT)", """CREATE TABLE IF NOT EXISTS skills ( name TEXT PRIMARY KEY, description TEXT, source TEXT, enabled INTEGER DEFAULT 1, installed_at INTEGER)""", """CREATE TABLE IF NOT EXISTS projects ( id TEXT PRIMARY KEY, name TEXT, instructions TEXT, created_at INTEGER, updated_at INTEGER)""", """CREATE TABLE IF NOT EXISTS project_files ( project_id TEXT NOT NULL, path TEXT NOT NULL, data TEXT, size INTEGER, updated_at INTEGER, PRIMARY KEY (project_id, path))""", """CREATE TABLE IF NOT EXISTS skill_files ( skill TEXT NOT NULL, path TEXT NOT NULL, content TEXT, PRIMARY KEY (skill, path))""", ] async def init_schema(): await db.batch([(s, None) for s in SCHEMA]) for col in ("model TEXT", "project_id TEXT"): # 舊資料庫升級 try: await db.execute(f"ALTER TABLE conversations ADD COLUMN {col}") except Exception: # noqa: BLE001 欄位已存在 pass # ---------- 對話 ---------- async def create_conversation(title: str, project_id: str | None = None) -> str: cid = uuid.uuid4().hex t = now_ms() await db.execute( "INSERT INTO conversations (id, title, created_at, updated_at, project_id) VALUES (?,?,?,?,?)", [cid, title or "新對話", t, t, project_id or None], ) return cid async def get_conversation(cid: str): rows = (await db.execute("SELECT * FROM conversations WHERE id = ?", [cid]))["rows"] return rows[0] if rows else None async def list_conversations(project: str = "all", limit: int = 200): """project: all=全部、none=未歸類、其他=專案 id""" where, args = "", [] if project == "none": where = "WHERE project_id IS NULL" elif project != "all": where, args = "WHERE project_id = ?", [project] return (await db.execute( f"SELECT id, title, model, project_id, updated_at FROM conversations {where} " "ORDER BY updated_at DESC LIMIT ?", args + [limit]))["rows"] async def set_conversation_model(cid: str, model: str | None): await db.execute("UPDATE conversations SET model = ? WHERE id = ?", [model or None, cid]) async def rename_conversation(cid: str, title: str): await db.execute("UPDATE conversations SET title = ? WHERE id = ?", [title, cid]) async def delete_conversation(cid: str): await db.batch([ ("DELETE FROM messages WHERE conversation_id = ?", [cid]), ("DELETE FROM conversations WHERE id = ?", [cid]), ]) async def add_message(cid, role, content, tool_calls=None, tool_call_id=None, name=None): t = now_ms() await db.batch([ ("INSERT INTO messages (conversation_id, role, content, tool_calls, tool_call_id, name, created_at) " "VALUES (?,?,?,?,?,?,?)", [cid, role, content, tool_calls, tool_call_id, name, t]), ("UPDATE conversations SET updated_at = ? WHERE id = ?", [t, cid]), ]) async def add_messages_tool_stopped(cid, calls): if not calls: return t = now_ms() await db.batch([("INSERT INTO messages (conversation_id, role, content, tool_calls, tool_call_id, name, created_at) " "VALUES (?,?,?,?,?,?,?)", [cid, "tool", '{"error": "使用者已停止"}', None, tc["id"], tc["function"]["name"], t]) for tc in calls]) async def count_messages(cid: str) -> int: rows = (await db.execute("SELECT COUNT(*) AS n FROM messages WHERE conversation_id = ?", [cid]))["rows"] return int(rows[0]["n"]) if rows else 0 async def get_messages(cid: str): return (await db.execute( "SELECT id, role, content, tool_calls, tool_call_id, name, created_at FROM messages " "WHERE conversation_id = ? ORDER BY id", [cid] ))["rows"] async def get_history(cid: str, limit: int): rows = (await db.execute( "SELECT * FROM (SELECT id, role, content, tool_calls, tool_call_id, name FROM messages " "WHERE conversation_id = ? ORDER BY id DESC LIMIT ?) ORDER BY id", [cid, limit] ))["rows"] while rows and rows[0]["role"] != "user": # 從 user 訊息開始,避免截斷到半個工具調用 rows.pop(0) return rows # ---------- 記憶 ---------- async def recent_memories(limit: int = 30): return (await db.execute( "SELECT id, content, tags, created_at FROM memories ORDER BY id DESC LIMIT ?", [limit] ))["rows"] async def add_memory(content: str, tags: str = "") -> int: r = await db.execute("INSERT INTO memories (content, tags, created_at) VALUES (?,?,?)", [content, tags, now_ms()]) return r["last_insert_rowid"] async def search_memories(query: str, limit: int = 10): words = [w for w in (query or "").split() if w][:6] if not words: return await recent_memories(limit) cond = " OR ".join(["content LIKE ? OR tags LIKE ?"] * len(words)) args: list = [] for w in words: args += [f"%{w}%", f"%{w}%"] return (await db.execute( f"SELECT id, content, tags, created_at FROM memories WHERE {cond} ORDER BY id DESC LIMIT ?", args + [limit], ))["rows"] async def delete_memory(mid: int) -> int: return (await db.execute("DELETE FROM memories WHERE id = ?", [mid]))["affected"] # ---------- 設定 ---------- async def get_setting(key: str): rows = (await db.execute("SELECT value FROM settings WHERE key = ?", [key]))["rows"] return rows[0]["value"] if rows else None async def set_setting(key: str, value: str | None): if value is None or value == "": await db.execute("DELETE FROM settings WHERE key = ?", [key]) else: await db.execute( "INSERT INTO settings (key, value) VALUES (?, ?) " "ON CONFLICT(key) DO UPDATE SET value = excluded.value", [key, value] ) # ---------- 技能 ---------- async def list_skills(enabled_only: bool = False): sql = "SELECT name, description, source, enabled, installed_at FROM skills" if enabled_only: sql += " WHERE enabled = 1" return (await db.execute(sql + " ORDER BY name"))["rows"] async def save_skill(name: str, description: str, source: str, files: dict[str, str]): stmts = [ ("DELETE FROM skill_files WHERE skill = ?", [name]), ("INSERT INTO skills (name, description, source, enabled, installed_at) VALUES (?,?,?,1,?) " "ON CONFLICT(name) DO UPDATE SET description = excluded.description, source = excluded.source, " "installed_at = excluded.installed_at", [name, description, source, now_ms()]), ] stmts += [("INSERT INTO skill_files (skill, path, content) VALUES (?,?,?)", [name, p, c]) for p, c in files.items()] for i in range(0, len(stmts), 50): await db.batch(stmts[i:i + 50]) async def get_skill_files(name: str): return (await db.execute("SELECT path, content FROM skill_files WHERE skill = ? ORDER BY path", [name]))["rows"] async def all_skill_files(): return (await db.execute("SELECT skill, path, content FROM skill_files"))["rows"] async def set_skill_enabled(name: str, enabled: bool): await db.execute("UPDATE skills SET enabled = ? WHERE name = ?", [1 if enabled else 0, name]) async def delete_skill(name: str): await db.batch([("DELETE FROM skill_files WHERE skill = ?", [name]), ("DELETE FROM skills WHERE name = ?", [name])]) # ---------- 專案 ---------- async def create_project(name: str, instructions: str = "") -> str: pid, t = uuid.uuid4().hex[:12], now_ms() await db.execute("INSERT INTO projects (id, name, instructions, created_at, updated_at) VALUES (?,?,?,?,?)", [pid, name or "未命名專案", instructions or "", t, t]) return pid async def list_projects(): return (await db.execute("SELECT id, name, instructions, updated_at FROM projects ORDER BY updated_at DESC"))["rows"] async def get_project(pid: str): rows = (await db.execute("SELECT * FROM projects WHERE id = ?", [pid]))["rows"] return rows[0] if rows else None async def update_project(pid: str, name: str | None = None, instructions: str | None = None): if name is not None: await db.execute("UPDATE projects SET name = ? WHERE id = ?", [name, pid]) if instructions is not None: await db.execute("UPDATE projects SET instructions = ? WHERE id = ?", [instructions, pid]) await touch_project(pid) async def touch_project(pid: str): await db.execute("UPDATE projects SET updated_at = ? WHERE id = ?", [now_ms(), pid]) async def delete_project(pid: str): """刪除專案和它的檔案;專案裡的對話保留,變成未歸類。""" await db.batch([("DELETE FROM project_files WHERE project_id = ?", [pid]), ("UPDATE conversations SET project_id = NULL WHERE project_id = ?", [pid]), ("DELETE FROM projects WHERE id = ?", [pid])]) async def list_project_files(pid: str, with_data: bool = False): cols = "path, size, updated_at" + (", data" if with_data else "") return (await db.execute(f"SELECT {cols} FROM project_files WHERE project_id = ? ORDER BY path", [pid]))["rows"] def upsert_file_stmt(pid: str, path: str, data_b64: str, size: int): return ("INSERT INTO project_files (project_id, path, data, size, updated_at) VALUES (?,?,?,?,?) " "ON CONFLICT(project_id, path) DO UPDATE SET data = excluded.data, size = excluded.size, " "updated_at = excluded.updated_at", [pid, path, data_b64, size, now_ms()]) def delete_file_stmt(pid: str, path: str): return ("DELETE FROM project_files WHERE project_id = ? AND path = ?", [pid, path])