File size: 13,179 Bytes
4d5692f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d0d1e07
 
 
 
 
 
 
 
 
 
 
 
 
 
4d5692f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
"""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])