Upload 15 files
Browse files- .dockerignore +4 -0
- Dockerfile +23 -21
- app/__init__.py +0 -0
- app/agent.py +186 -0
- app/auth.py +66 -0
- app/config.py +57 -0
- app/db.py +321 -0
- app/main.py +375 -0
- app/mcp_client.py +188 -0
- app/providers.py +105 -0
- app/skills.py +205 -0
- app/static/index.html +601 -0
- app/tools.py +342 -0
- app/workspace.py +182 -0
- requirements.txt +12 -5
.dockerignore
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__
|
| 2 |
+
*.pyc
|
| 3 |
+
.env
|
| 4 |
+
.git
|
Dockerfile
CHANGED
|
@@ -1,27 +1,29 @@
|
|
| 1 |
-
# Use Python 3.11 slim image
|
| 2 |
FROM python:3.11-slim
|
| 3 |
|
| 4 |
-
|
| 5 |
-
|
|
|
|
| 6 |
|
| 7 |
-
#
|
| 8 |
-
RUN apt-get update && apt-get install -y \
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
|
| 13 |
-
|
| 14 |
-
|
|
|
|
| 15 |
|
| 16 |
-
#
|
| 17 |
-
RUN
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
# Create non-root user for security
|
| 23 |
-
RUN useradd -m appuser && chown -R appuser /app
|
| 24 |
-
USER appuser
|
| 25 |
-
|
| 26 |
-
# Hugging Face requires apps to run on port 7860
|
| 27 |
-
CMD uvicorn app:app --host 0.0.0.0 --port 7860
|
|
|
|
|
|
|
| 1 |
FROM python:3.11-slim
|
| 2 |
|
| 3 |
+
ENV PYTHONDONTWRITEBYTECODE=1 \
|
| 4 |
+
PYTHONUNBUFFERED=1 \
|
| 5 |
+
PIP_NO_CACHE_DIR=1
|
| 6 |
|
| 7 |
+
# Node.js 22(給 npx 類 MCP 伺服器 / 技能腳本)+ 常用工具
|
| 8 |
+
RUN apt-get update && apt-get install -y --no-install-recommends curl ca-certificates git gnupg \
|
| 9 |
+
&& curl -fsSL https://deb.nodesource.com/setup_22.x | bash - \
|
| 10 |
+
&& apt-get install -y --no-install-recommends nodejs \
|
| 11 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 12 |
|
| 13 |
+
COPY requirements.txt /tmp/requirements.txt
|
| 14 |
+
# uv 提供 uvx(給 Python 類 MCP 伺服器)
|
| 15 |
+
RUN pip install --upgrade pip && pip install -r /tmp/requirements.txt uv
|
| 16 |
|
| 17 |
+
# HF Spaces 以 uid 1000 執行
|
| 18 |
+
RUN useradd -m -u 1000 user
|
| 19 |
+
USER user
|
| 20 |
+
ENV HOME=/home/user \
|
| 21 |
+
PATH=/home/user/.local/bin:$PATH \
|
| 22 |
+
NPM_CONFIG_CACHE=/home/user/.npm \
|
| 23 |
+
WORKDIR=/home/user/workspace \
|
| 24 |
+
SKILLS_DIR=/home/user/skills
|
| 25 |
+
WORKDIR /home/user/app
|
| 26 |
+
COPY --chown=user . .
|
| 27 |
|
| 28 |
+
EXPOSE 7860
|
| 29 |
+
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "7860", "--proxy-headers", "--forwarded-allow-ips", "*"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
app/__init__.py
ADDED
|
File without changes
|
app/agent.py
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Agent 主循環:串流呼叫 LLM → 若有工具調用就執行 → 把結果餵回去 → 直到給出最終回答。"""
|
| 2 |
+
import json
|
| 3 |
+
from datetime import datetime
|
| 4 |
+
from zoneinfo import ZoneInfo
|
| 5 |
+
|
| 6 |
+
import httpx
|
| 7 |
+
|
| 8 |
+
from . import config
|
| 9 |
+
from . import db as store
|
| 10 |
+
from . import providers
|
| 11 |
+
from . import workspace
|
| 12 |
+
from .tools import execute_tool, tool_schemas
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class LLMError(Exception):
|
| 16 |
+
pass
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
async def build_system_prompt(project: dict | None = None) -> str:
|
| 20 |
+
sp = await store.get_setting("system_prompt") or config.DEFAULT_SYSTEM_PROMPT
|
| 21 |
+
try:
|
| 22 |
+
now = datetime.now(ZoneInfo(config.DEFAULT_TZ)).strftime("%Y-%m-%d %H:%M (%A)")
|
| 23 |
+
except Exception:
|
| 24 |
+
now = datetime.utcnow().strftime("%Y-%m-%d %H:%M UTC")
|
| 25 |
+
sp += f"\n\n目前時間:{now},時區 {config.DEFAULT_TZ}。"
|
| 26 |
+
skills = await store.list_skills(enabled_only=True)
|
| 27 |
+
if skills:
|
| 28 |
+
sp += ("\n\n## 已安裝的技能(Skills)\n任務符合下列描述時,先呼叫 load_skill(name) 讀取完整說明再執行:\n"
|
| 29 |
+
+ "\n".join(f"- {s['name']}: {s['description']}" for s in skills))
|
| 30 |
+
if project:
|
| 31 |
+
files = workspace.tree(project["id"], limit=200)
|
| 32 |
+
sp += (f"\n\n## 目前專案:{project['name']}\n"
|
| 33 |
+
f"工作目錄(run_python / run_shell 的 cwd,檔案工具的根目錄)就是這個專案的資料夾,改動會自動永久保存。\n")
|
| 34 |
+
if project.get("instructions"):
|
| 35 |
+
sp += f"\n### 專案說明(使用者寫的,必須遵守)\n{project['instructions']}\n"
|
| 36 |
+
sp += "\n### 專案檔案\n" + ("\n".join(f"- {f}" for f in files) if files else "(目前是空的)")
|
| 37 |
+
else:
|
| 38 |
+
sp += "\n\n(這個對話不屬於任何專案:工作目錄是暫存區,容器重啟後檔案會消失。要保存檔案請使用者建立專案。)"
|
| 39 |
+
mems = await store.recent_memories(30)
|
| 40 |
+
if mems:
|
| 41 |
+
sp += "\n\n## 已知的使用者長期記憶([id] 內容)\n" + "\n".join(
|
| 42 |
+
f"- [{m['id']}] {m['content']}" for m in reversed(mems))
|
| 43 |
+
return sp
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def rows_to_messages(rows: list[dict]) -> list[dict]:
|
| 47 |
+
"""把資料庫列轉成 OpenAI messages,並清掉不完整的工具調用(例如中途中斷)。"""
|
| 48 |
+
msgs = []
|
| 49 |
+
for r in rows:
|
| 50 |
+
if r["role"] == "assistant":
|
| 51 |
+
m = {"role": "assistant", "content": r["content"] or ""}
|
| 52 |
+
if r["tool_calls"]:
|
| 53 |
+
m["tool_calls"] = json.loads(r["tool_calls"])
|
| 54 |
+
m["content"] = r["content"] or None
|
| 55 |
+
msgs.append(m)
|
| 56 |
+
elif r["role"] == "tool":
|
| 57 |
+
msgs.append({"role": "tool", "tool_call_id": r["tool_call_id"], "content": r["content"] or ""})
|
| 58 |
+
else:
|
| 59 |
+
msgs.append({"role": r["role"], "content": r["content"] or ""})
|
| 60 |
+
|
| 61 |
+
clean, i = [], 0
|
| 62 |
+
while i < len(msgs):
|
| 63 |
+
m = msgs[i]
|
| 64 |
+
if m["role"] == "assistant" and m.get("tool_calls"):
|
| 65 |
+
ids = {tc["id"] for tc in m["tool_calls"]}
|
| 66 |
+
j, results = i + 1, []
|
| 67 |
+
while j < len(msgs) and msgs[j]["role"] == "tool":
|
| 68 |
+
results.append(msgs[j])
|
| 69 |
+
j += 1
|
| 70 |
+
if ids <= {t["tool_call_id"] for t in results}:
|
| 71 |
+
clean.append(m)
|
| 72 |
+
clean.extend(t for t in results if t["tool_call_id"] in ids)
|
| 73 |
+
elif m["content"]:
|
| 74 |
+
clean.append({"role": "assistant", "content": m["content"]})
|
| 75 |
+
i = j
|
| 76 |
+
continue
|
| 77 |
+
if m["role"] == "tool": # 孤立的工具結果
|
| 78 |
+
i += 1
|
| 79 |
+
continue
|
| 80 |
+
clean.append(m)
|
| 81 |
+
i += 1
|
| 82 |
+
return clean
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def _clean_schema(o):
|
| 86 |
+
"""去掉部分提供商(如 Gemini)不接受的 JSON Schema 欄位。"""
|
| 87 |
+
if isinstance(o, dict):
|
| 88 |
+
return {k: _clean_schema(v) for k, v in o.items() if k not in ("$schema", "$id")}
|
| 89 |
+
if isinstance(o, list):
|
| 90 |
+
return [_clean_schema(v) for v in o]
|
| 91 |
+
return o
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
async def stream_completion(client, provider, model, messages, tools, tool_choice=None):
|
| 95 |
+
body = {"model": model, "messages": messages, "stream": True}
|
| 96 |
+
if tools:
|
| 97 |
+
body["tools"] = tools
|
| 98 |
+
if tool_choice:
|
| 99 |
+
body["tool_choice"] = tool_choice
|
| 100 |
+
headers = {"Authorization": f"Bearer {providers.key_of(provider)}"}
|
| 101 |
+
async with client.stream("POST", f"{provider['base_url']}/chat/completions",
|
| 102 |
+
json=body, headers=headers) as r:
|
| 103 |
+
if r.status_code >= 400:
|
| 104 |
+
txt = (await r.aread()).decode(errors="replace")
|
| 105 |
+
raise LLMError(f"{provider['name']} / {model} 回傳 HTTP {r.status_code}:{txt[:300]}(可在頂欄換模型後重試)")
|
| 106 |
+
async for line in r.aiter_lines():
|
| 107 |
+
line = line.strip()
|
| 108 |
+
if not line.startswith("data:"):
|
| 109 |
+
continue
|
| 110 |
+
data = line[5:].strip()
|
| 111 |
+
if data == "[DONE]":
|
| 112 |
+
break
|
| 113 |
+
try:
|
| 114 |
+
chunk = json.loads(data)
|
| 115 |
+
except json.JSONDecodeError:
|
| 116 |
+
continue
|
| 117 |
+
if chunk.get("error"):
|
| 118 |
+
raise LLMError(str(chunk["error"])[:300])
|
| 119 |
+
yield chunk
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
async def run_agent(conv_id: str, user_text: str, model: str | None = None):
|
| 123 |
+
"""非同步產生器,逐一 yield 事件:reasoning / token / tool_start / tool_result / done / error。"""
|
| 124 |
+
await store.add_message(conv_id, "user", user_text)
|
| 125 |
+
history = await store.get_history(conv_id, config.HISTORY_LIMIT)
|
| 126 |
+
chosen = await providers.resolve(model)
|
| 127 |
+
if not chosen:
|
| 128 |
+
yield {"type": "error", "message": "還沒選模型:請先在「🤖 模型」面板加提供商、拉取並勾選模型,再在頂欄選一個。"}
|
| 129 |
+
return
|
| 130 |
+
provider, model_id = chosen
|
| 131 |
+
conv = await store.get_conversation(conv_id) or {}
|
| 132 |
+
project = await store.get_project(conv["project_id"]) if conv.get("project_id") else None
|
| 133 |
+
workspace.current_project.set(project["id"] if project else None)
|
| 134 |
+
if project:
|
| 135 |
+
await workspace.restore(project["id"])
|
| 136 |
+
messages = [{"role": "system", "content": await build_system_prompt(project)}] + rows_to_messages(history)
|
| 137 |
+
tools = _clean_schema(tool_schemas())
|
| 138 |
+
|
| 139 |
+
async with httpx.AsyncClient(timeout=httpx.Timeout(300, connect=20)) as client:
|
| 140 |
+
for step in range(config.MAX_AGENT_STEPS):
|
| 141 |
+
last_step = step == config.MAX_AGENT_STEPS - 1
|
| 142 |
+
content, calls = "", {}
|
| 143 |
+
async for chunk in stream_completion(client, provider, model_id, messages, tools,
|
| 144 |
+
"none" if last_step else None):
|
| 145 |
+
choices = chunk.get("choices") or []
|
| 146 |
+
if not choices:
|
| 147 |
+
continue
|
| 148 |
+
delta = choices[0].get("delta") or {}
|
| 149 |
+
reasoning = delta.get("reasoning_content") or delta.get("reasoning")
|
| 150 |
+
if reasoning:
|
| 151 |
+
yield {"type": "reasoning", "text": reasoning}
|
| 152 |
+
if delta.get("content"):
|
| 153 |
+
content += delta["content"]
|
| 154 |
+
yield {"type": "token", "text": delta["content"]}
|
| 155 |
+
for tc in delta.get("tool_calls") or []:
|
| 156 |
+
slot = calls.setdefault(tc.get("index", 0), {
|
| 157 |
+
"id": "", "type": "function", "function": {"name": "", "arguments": ""}})
|
| 158 |
+
if tc.get("id"):
|
| 159 |
+
slot["id"] = tc["id"]
|
| 160 |
+
fn = tc.get("function") or {}
|
| 161 |
+
if fn.get("name") and not slot["function"]["name"]:
|
| 162 |
+
slot["function"]["name"] = fn["name"]
|
| 163 |
+
if fn.get("arguments"):
|
| 164 |
+
slot["function"]["arguments"] += fn["arguments"]
|
| 165 |
+
|
| 166 |
+
tool_calls = [calls[k] for k in sorted(calls)]
|
| 167 |
+
for n, tc in enumerate(tool_calls):
|
| 168 |
+
tc["id"] = tc["id"] or f"call_{step}_{n}"
|
| 169 |
+
|
| 170 |
+
if not tool_calls:
|
| 171 |
+
await store.add_message(conv_id, "assistant", content)
|
| 172 |
+
yield {"type": "done"}
|
| 173 |
+
return
|
| 174 |
+
|
| 175 |
+
await store.add_message(conv_id, "assistant", content,
|
| 176 |
+
tool_calls=json.dumps(tool_calls, ensure_ascii=False))
|
| 177 |
+
messages.append({"role": "assistant", "content": content or None, "tool_calls": tool_calls})
|
| 178 |
+
for tc in tool_calls:
|
| 179 |
+
name, args = tc["function"]["name"], tc["function"]["arguments"]
|
| 180 |
+
yield {"type": "tool_start", "id": tc["id"], "name": name, "arguments": args}
|
| 181 |
+
result = await execute_tool(name, args)
|
| 182 |
+
yield {"type": "tool_result", "id": tc["id"], "name": name, "result": result[:4000]}
|
| 183 |
+
await store.add_message(conv_id, "tool", result, tool_call_id=tc["id"], name=name)
|
| 184 |
+
messages.append({"role": "tool", "tool_call_id": tc["id"], "content": result})
|
| 185 |
+
|
| 186 |
+
yield {"type": "error", "message": f"已達最大步數({config.MAX_AGENT_STEPS}),可調高 MAX_AGENT_STEPS"}
|
app/auth.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""密碼登入 + HMAC 簽名 token(存在瀏覽器 localStorage,以 Bearer 送出,HF 的 iframe 裡也能用)。"""
|
| 2 |
+
import hashlib
|
| 3 |
+
import hmac
|
| 4 |
+
import time
|
| 5 |
+
|
| 6 |
+
from fastapi import Header, HTTPException, Request
|
| 7 |
+
|
| 8 |
+
from . import config
|
| 9 |
+
|
| 10 |
+
_KEY = hashlib.sha256(("session:" + config.APP_SECRET).encode()).digest()
|
| 11 |
+
_fails: dict[str, list] = {} # ip -> [失敗次數, 第一次失敗時間]
|
| 12 |
+
MAX_FAILS, LOCK_SECONDS = 5, 600
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def issue_token() -> str:
|
| 16 |
+
exp = str(int(time.time()) + config.SESSION_DAYS * 86400)
|
| 17 |
+
sig = hmac.new(_KEY, exp.encode(), hashlib.sha256).hexdigest()
|
| 18 |
+
return f"{exp}.{sig}"
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def verify_token(token: str) -> bool:
|
| 22 |
+
try:
|
| 23 |
+
exp, sig = token.split(".", 1)
|
| 24 |
+
if int(exp) < time.time():
|
| 25 |
+
return False
|
| 26 |
+
except ValueError:
|
| 27 |
+
return False
|
| 28 |
+
good = hmac.new(_KEY, exp.encode(), hashlib.sha256).hexdigest()
|
| 29 |
+
return hmac.compare_digest(good, sig)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def check_secret(secret: str) -> bool:
|
| 33 |
+
a = hashlib.sha256((secret or "").encode()).digest()
|
| 34 |
+
b = hashlib.sha256(config.APP_SECRET.encode()).digest()
|
| 35 |
+
return bool(config.APP_SECRET) and hmac.compare_digest(a, b)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def client_ip(req: Request) -> str:
|
| 39 |
+
xff = req.headers.get("x-forwarded-for")
|
| 40 |
+
if xff:
|
| 41 |
+
return xff.split(",")[0].strip()
|
| 42 |
+
return req.client.host if req.client else "unknown"
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def is_locked(ip: str) -> bool:
|
| 46 |
+
rec = _fails.get(ip)
|
| 47 |
+
if not rec:
|
| 48 |
+
return False
|
| 49 |
+
if time.time() - rec[1] > LOCK_SECONDS:
|
| 50 |
+
_fails.pop(ip, None)
|
| 51 |
+
return False
|
| 52 |
+
return rec[0] >= MAX_FAILS
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def record_fail(ip: str):
|
| 56 |
+
rec = _fails.setdefault(ip, [0, time.time()])
|
| 57 |
+
rec[0] += 1
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def clear_fails(ip: str):
|
| 61 |
+
_fails.pop(ip, None)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
async def require_auth(authorization: str | None = Header(default=None)):
|
| 65 |
+
if not authorization or not authorization.startswith("Bearer ") or not verify_token(authorization[7:]):
|
| 66 |
+
raise HTTPException(status_code=401, detail="未授權")
|
app/config.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""所有設定都從環境變數讀取(在 Hugging Face Space 的 Settings → Secrets 裡設定)。"""
|
| 2 |
+
import os
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def _bool(v: str | None, default: bool) -> bool:
|
| 6 |
+
if v is None or v == "":
|
| 7 |
+
return default
|
| 8 |
+
return v.strip().lower() in ("1", "true", "yes", "on")
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
# 必填
|
| 12 |
+
APP_SECRET = os.getenv("APP_SECRET", "") # 前端登入密碼
|
| 13 |
+
TURSO_DATABASE_URL = os.getenv("TURSO_DATABASE_URL", "") # libsql://xxx.turso.io
|
| 14 |
+
TURSO_AUTH_TOKEN = os.getenv("TURSO_AUTH_TOKEN", "")
|
| 15 |
+
# 模型不用環境變數:全部在前端「🤖 模型」面板裡新增(存在 Turso)
|
| 16 |
+
|
| 17 |
+
# 選填
|
| 18 |
+
TAVILY_API_KEY = os.getenv("TAVILY_API_KEY", "") # 有就用 Tavily 搜尋,沒有就用 ddgs
|
| 19 |
+
MAX_AGENT_STEPS = int(os.getenv("MAX_AGENT_STEPS", "8")) # 單次回覆最多幾輪工具調用
|
| 20 |
+
ENABLE_PYTHON_TOOL = _bool(os.getenv("ENABLE_PYTHON_TOOL"), True)
|
| 21 |
+
SESSION_DAYS = int(os.getenv("SESSION_DAYS", "30")) # 登入有效天數
|
| 22 |
+
HISTORY_LIMIT = int(os.getenv("HISTORY_LIMIT", "60")) # 帶入上下文的歷史訊息數
|
| 23 |
+
DEFAULT_TZ = os.getenv("DEFAULT_TZ", "Asia/Hong_Kong")
|
| 24 |
+
ENABLE_SHELL_TOOL = _bool(os.getenv("ENABLE_SHELL_TOOL"), True)
|
| 25 |
+
WORKDIR = os.getenv("WORKDIR", "/tmp/workspace") # run_python / run_shell 的工作目錄
|
| 26 |
+
SKILLS_DIR = os.getenv("SKILLS_DIR", "/tmp/skills") # 技能檔案落地目錄
|
| 27 |
+
GITHUB_TOKEN = os.getenv("GITHUB_TOKEN", "") # 選填:安裝私有 repo 的技能
|
| 28 |
+
# 首次啟動自動安裝的技能(逗號分隔的 GitHub 資料夾網址;設成空字串可停用)。
|
| 29 |
+
# 已裝過或你手動刪掉的不會重裝。預設是一組開發向技能。
|
| 30 |
+
_DEV_SKILLS = ",".join(
|
| 31 |
+
[f"https://github.com/obra/superpowers/tree/main/skills/{n}" for n in (
|
| 32 |
+
"brainstorming", "writing-plans", "executing-plans", "test-driven-development",
|
| 33 |
+
"systematic-debugging", "requesting-code-review", "receiving-code-review",
|
| 34 |
+
"verification-before-completion")]
|
| 35 |
+
+ [f"https://github.com/anthropics/skills/tree/main/skills/{n}" for n in (
|
| 36 |
+
"mcp-builder", "frontend-design", "skill-creator")])
|
| 37 |
+
DEFAULT_SKILLS = [u.strip() for u in os.getenv("DEFAULT_SKILLS", _DEV_SKILLS).split(",") if u.strip()]
|
| 38 |
+
PROJECT_MAX_FILE_MB = int(os.getenv("PROJECT_MAX_FILE_MB", "5")) # 單檔超過就不存進資料庫
|
| 39 |
+
PROJECT_MAX_TOTAL_MB = int(os.getenv("PROJECT_MAX_TOTAL_MB", "100")) # 每個專案存進資料庫的上限
|
| 40 |
+
MCP_CONNECT_TIMEOUT = int(os.getenv("MCP_CONNECT_TIMEOUT", "60"))
|
| 41 |
+
MCP_CALL_TIMEOUT = int(os.getenv("MCP_CALL_TIMEOUT", "120"))
|
| 42 |
+
|
| 43 |
+
DEFAULT_SYSTEM_PROMPT = os.getenv(
|
| 44 |
+
"SYSTEM_PROMPT",
|
| 45 |
+
"""你是使用者的私人 AI 助理(AI agent),可以調用工具完成任務。
|
| 46 |
+
|
| 47 |
+
原則:
|
| 48 |
+
- 需要最新資訊、事實核查時,先用 web_search,再用 fetch_url 讀原文,回答時附上來源網址。
|
| 49 |
+
- 需要計算、處理資料、畫圖或驗證程式時,用 run_python 實際執行,不要心算。
|
| 50 |
+
- 寫程式時:用 list_files / read_file 先看清楚現有程式,用 write_file / edit_file 改檔案,用 run_shell 跑測試、裝依賴、執行;改完要實際跑過驗證。
|
| 51 |
+
- 檔案都在目前專案資料夾(也是 run_python / run_shell 的工作目錄),會自動永久保存。
|
| 52 |
+
- 使用者告訴你值得長期記住的事(偏好、身份、長期計劃)時,用 save_memory 存下來;需要回想時用 search_memory。
|
| 53 |
+
- 任務符合某個技能(Skill)的描述時,先用 load_skill 讀完整說明,再照著做。
|
| 54 |
+
- MCP 工具(名稱以 mcp_ 開頭)是外部服務,按其描述使用。
|
| 55 |
+
- 回答用使用者的語言,簡潔、直接,善用 Markdown。
|
| 56 |
+
""",
|
| 57 |
+
)
|
app/db.py
ADDED
|
@@ -0,0 +1,321 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Turso(libSQL)資料庫:直接走 Hrana-over-HTTP(/v2/pipeline),不需要原生驅動。"""
|
| 2 |
+
import json
|
| 3 |
+
import time
|
| 4 |
+
import uuid
|
| 5 |
+
|
| 6 |
+
import httpx
|
| 7 |
+
|
| 8 |
+
from . import config
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def now_ms() -> int:
|
| 12 |
+
return int(time.time() * 1000)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class Turso:
|
| 16 |
+
def __init__(self, url: str, token: str):
|
| 17 |
+
url = (url or "").strip()
|
| 18 |
+
if url.startswith("libsql://"):
|
| 19 |
+
url = "https://" + url[len("libsql://"):]
|
| 20 |
+
self.endpoint = url.rstrip("/") + "/v2/pipeline"
|
| 21 |
+
self.headers = {"Authorization": f"Bearer {token}"}
|
| 22 |
+
self.client = httpx.AsyncClient(timeout=httpx.Timeout(30, connect=10))
|
| 23 |
+
|
| 24 |
+
@staticmethod
|
| 25 |
+
def _arg(v):
|
| 26 |
+
if v is None:
|
| 27 |
+
return {"type": "null"}
|
| 28 |
+
if isinstance(v, bool):
|
| 29 |
+
return {"type": "integer", "value": str(int(v))}
|
| 30 |
+
if isinstance(v, int):
|
| 31 |
+
return {"type": "integer", "value": str(v)}
|
| 32 |
+
if isinstance(v, float):
|
| 33 |
+
return {"type": "float", "value": v}
|
| 34 |
+
return {"type": "text", "value": str(v)}
|
| 35 |
+
|
| 36 |
+
@staticmethod
|
| 37 |
+
def _val(v):
|
| 38 |
+
t = v.get("type")
|
| 39 |
+
if t == "null":
|
| 40 |
+
return None
|
| 41 |
+
if t == "integer":
|
| 42 |
+
return int(v["value"])
|
| 43 |
+
if t == "float":
|
| 44 |
+
return float(v["value"])
|
| 45 |
+
if t == "blob":
|
| 46 |
+
return v.get("base64")
|
| 47 |
+
return v.get("value")
|
| 48 |
+
|
| 49 |
+
async def batch(self, stmts: list[tuple[str, list | None]]) -> list[dict]:
|
| 50 |
+
reqs = [
|
| 51 |
+
{"type": "execute", "stmt": {"sql": sql, "args": [self._arg(a) for a in (args or [])]}}
|
| 52 |
+
for sql, args in stmts
|
| 53 |
+
]
|
| 54 |
+
reqs.append({"type": "close"})
|
| 55 |
+
r = await self.client.post(self.endpoint, headers=self.headers, json={"requests": reqs})
|
| 56 |
+
if r.status_code >= 400:
|
| 57 |
+
raise RuntimeError(f"Turso HTTP {r.status_code}: {r.text[:300]}")
|
| 58 |
+
out = []
|
| 59 |
+
for res in r.json()["results"][:-1]:
|
| 60 |
+
if res.get("type") == "error":
|
| 61 |
+
raise RuntimeError(f"Turso SQL 錯誤: {res['error'].get('message')}")
|
| 62 |
+
result = res["response"]["result"]
|
| 63 |
+
cols = [c.get("name") for c in result.get("cols", [])]
|
| 64 |
+
rows = [{c: self._val(v) for c, v in zip(cols, row)} for row in result.get("rows", [])]
|
| 65 |
+
rid = result.get("last_insert_rowid")
|
| 66 |
+
out.append({
|
| 67 |
+
"rows": rows,
|
| 68 |
+
"last_insert_rowid": int(rid) if rid is not None else None,
|
| 69 |
+
"affected": result.get("affected_row_count", 0),
|
| 70 |
+
})
|
| 71 |
+
return out
|
| 72 |
+
|
| 73 |
+
async def execute(self, sql: str, args: list | None = None) -> dict:
|
| 74 |
+
return (await self.batch([(sql, args)]))[0]
|
| 75 |
+
|
| 76 |
+
async def close(self):
|
| 77 |
+
await self.client.aclose()
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
db = Turso(config.TURSO_DATABASE_URL, config.TURSO_AUTH_TOKEN)
|
| 81 |
+
|
| 82 |
+
SCHEMA = [
|
| 83 |
+
"""CREATE TABLE IF NOT EXISTS conversations (
|
| 84 |
+
id TEXT PRIMARY KEY, title TEXT, created_at INTEGER, updated_at INTEGER)""",
|
| 85 |
+
"""CREATE TABLE IF NOT EXISTS messages (
|
| 86 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 87 |
+
conversation_id TEXT NOT NULL,
|
| 88 |
+
role TEXT NOT NULL,
|
| 89 |
+
content TEXT,
|
| 90 |
+
tool_calls TEXT,
|
| 91 |
+
tool_call_id TEXT,
|
| 92 |
+
name TEXT,
|
| 93 |
+
created_at INTEGER)""",
|
| 94 |
+
"CREATE INDEX IF NOT EXISTS idx_messages_conv ON messages(conversation_id, id)",
|
| 95 |
+
"""CREATE TABLE IF NOT EXISTS memories (
|
| 96 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT, content TEXT NOT NULL, tags TEXT, created_at INTEGER)""",
|
| 97 |
+
"CREATE TABLE IF NOT EXISTS settings (key TEXT PRIMARY KEY, value TEXT)",
|
| 98 |
+
"""CREATE TABLE IF NOT EXISTS skills (
|
| 99 |
+
name TEXT PRIMARY KEY, description TEXT, source TEXT, enabled INTEGER DEFAULT 1, installed_at INTEGER)""",
|
| 100 |
+
"""CREATE TABLE IF NOT EXISTS projects (
|
| 101 |
+
id TEXT PRIMARY KEY, name TEXT, instructions TEXT, created_at INTEGER, updated_at INTEGER)""",
|
| 102 |
+
"""CREATE TABLE IF NOT EXISTS project_files (
|
| 103 |
+
project_id TEXT NOT NULL, path TEXT NOT NULL, data TEXT, size INTEGER, updated_at INTEGER,
|
| 104 |
+
PRIMARY KEY (project_id, path))""",
|
| 105 |
+
"""CREATE TABLE IF NOT EXISTS skill_files (
|
| 106 |
+
skill TEXT NOT NULL, path TEXT NOT NULL, content TEXT, PRIMARY KEY (skill, path))""",
|
| 107 |
+
]
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
async def init_schema():
|
| 111 |
+
await db.batch([(s, None) for s in SCHEMA])
|
| 112 |
+
for col in ("model TEXT", "project_id TEXT"): # 舊資料庫升級
|
| 113 |
+
try:
|
| 114 |
+
await db.execute(f"ALTER TABLE conversations ADD COLUMN {col}")
|
| 115 |
+
except Exception: # noqa: BLE001 欄位已存在
|
| 116 |
+
pass
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
# ---------- 對話 ----------
|
| 120 |
+
async def create_conversation(title: str, project_id: str | None = None) -> str:
|
| 121 |
+
cid = uuid.uuid4().hex
|
| 122 |
+
t = now_ms()
|
| 123 |
+
await db.execute(
|
| 124 |
+
"INSERT INTO conversations (id, title, created_at, updated_at, project_id) VALUES (?,?,?,?,?)",
|
| 125 |
+
[cid, title or "新對話", t, t, project_id or None],
|
| 126 |
+
)
|
| 127 |
+
return cid
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
async def get_conversation(cid: str):
|
| 131 |
+
rows = (await db.execute("SELECT * FROM conversations WHERE id = ?", [cid]))["rows"]
|
| 132 |
+
return rows[0] if rows else None
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
async def list_conversations(project: str = "all", limit: int = 200):
|
| 136 |
+
"""project: all=全部、none=未歸類、其他=專案 id"""
|
| 137 |
+
where, args = "", []
|
| 138 |
+
if project == "none":
|
| 139 |
+
where = "WHERE project_id IS NULL"
|
| 140 |
+
elif project != "all":
|
| 141 |
+
where, args = "WHERE project_id = ?", [project]
|
| 142 |
+
return (await db.execute(
|
| 143 |
+
f"SELECT id, title, model, project_id, updated_at FROM conversations {where} "
|
| 144 |
+
"ORDER BY updated_at DESC LIMIT ?", args + [limit]))["rows"]
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
async def set_conversation_model(cid: str, model: str | None):
|
| 148 |
+
await db.execute("UPDATE conversations SET model = ? WHERE id = ?", [model or None, cid])
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
async def rename_conversation(cid: str, title: str):
|
| 152 |
+
await db.execute("UPDATE conversations SET title = ? WHERE id = ?", [title, cid])
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
async def delete_conversation(cid: str):
|
| 156 |
+
await db.batch([
|
| 157 |
+
("DELETE FROM messages WHERE conversation_id = ?", [cid]),
|
| 158 |
+
("DELETE FROM conversations WHERE id = ?", [cid]),
|
| 159 |
+
])
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
async def add_message(cid, role, content, tool_calls=None, tool_call_id=None, name=None):
|
| 163 |
+
t = now_ms()
|
| 164 |
+
await db.batch([
|
| 165 |
+
("INSERT INTO messages (conversation_id, role, content, tool_calls, tool_call_id, name, created_at) "
|
| 166 |
+
"VALUES (?,?,?,?,?,?,?)", [cid, role, content, tool_calls, tool_call_id, name, t]),
|
| 167 |
+
("UPDATE conversations SET updated_at = ? WHERE id = ?", [t, cid]),
|
| 168 |
+
])
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
async def get_messages(cid: str):
|
| 172 |
+
return (await db.execute(
|
| 173 |
+
"SELECT id, role, content, tool_calls, tool_call_id, name, created_at FROM messages "
|
| 174 |
+
"WHERE conversation_id = ? ORDER BY id", [cid]
|
| 175 |
+
))["rows"]
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
async def get_history(cid: str, limit: int):
|
| 179 |
+
rows = (await db.execute(
|
| 180 |
+
"SELECT * FROM (SELECT id, role, content, tool_calls, tool_call_id, name FROM messages "
|
| 181 |
+
"WHERE conversation_id = ? ORDER BY id DESC LIMIT ?) ORDER BY id", [cid, limit]
|
| 182 |
+
))["rows"]
|
| 183 |
+
while rows and rows[0]["role"] != "user": # 從 user 訊息開始,避免截斷到半個工具調用
|
| 184 |
+
rows.pop(0)
|
| 185 |
+
return rows
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
# ---------- 記憶 ----------
|
| 189 |
+
async def recent_memories(limit: int = 30):
|
| 190 |
+
return (await db.execute(
|
| 191 |
+
"SELECT id, content, tags, created_at FROM memories ORDER BY id DESC LIMIT ?", [limit]
|
| 192 |
+
))["rows"]
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
async def add_memory(content: str, tags: str = "") -> int:
|
| 196 |
+
r = await db.execute("INSERT INTO memories (content, tags, created_at) VALUES (?,?,?)",
|
| 197 |
+
[content, tags, now_ms()])
|
| 198 |
+
return r["last_insert_rowid"]
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
async def search_memories(query: str, limit: int = 10):
|
| 202 |
+
words = [w for w in (query or "").split() if w][:6]
|
| 203 |
+
if not words:
|
| 204 |
+
return await recent_memories(limit)
|
| 205 |
+
cond = " OR ".join(["content LIKE ? OR tags LIKE ?"] * len(words))
|
| 206 |
+
args: list = []
|
| 207 |
+
for w in words:
|
| 208 |
+
args += [f"%{w}%", f"%{w}%"]
|
| 209 |
+
return (await db.execute(
|
| 210 |
+
f"SELECT id, content, tags, created_at FROM memories WHERE {cond} ORDER BY id DESC LIMIT ?",
|
| 211 |
+
args + [limit],
|
| 212 |
+
))["rows"]
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
async def delete_memory(mid: int) -> int:
|
| 216 |
+
return (await db.execute("DELETE FROM memories WHERE id = ?", [mid]))["affected"]
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
# ---------- 設定 ----------
|
| 220 |
+
async def get_setting(key: str):
|
| 221 |
+
rows = (await db.execute("SELECT value FROM settings WHERE key = ?", [key]))["rows"]
|
| 222 |
+
return rows[0]["value"] if rows else None
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
async def set_setting(key: str, value: str | None):
|
| 226 |
+
if value is None or value == "":
|
| 227 |
+
await db.execute("DELETE FROM settings WHERE key = ?", [key])
|
| 228 |
+
else:
|
| 229 |
+
await db.execute(
|
| 230 |
+
"INSERT INTO settings (key, value) VALUES (?, ?) "
|
| 231 |
+
"ON CONFLICT(key) DO UPDATE SET value = excluded.value", [key, value]
|
| 232 |
+
)
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
# ---------- 技能 ----------
|
| 236 |
+
async def list_skills(enabled_only: bool = False):
|
| 237 |
+
sql = "SELECT name, description, source, enabled, installed_at FROM skills"
|
| 238 |
+
if enabled_only:
|
| 239 |
+
sql += " WHERE enabled = 1"
|
| 240 |
+
return (await db.execute(sql + " ORDER BY name"))["rows"]
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
async def save_skill(name: str, description: str, source: str, files: dict[str, str]):
|
| 244 |
+
stmts = [
|
| 245 |
+
("DELETE FROM skill_files WHERE skill = ?", [name]),
|
| 246 |
+
("INSERT INTO skills (name, description, source, enabled, installed_at) VALUES (?,?,?,1,?) "
|
| 247 |
+
"ON CONFLICT(name) DO UPDATE SET description = excluded.description, source = excluded.source, "
|
| 248 |
+
"installed_at = excluded.installed_at", [name, description, source, now_ms()]),
|
| 249 |
+
]
|
| 250 |
+
stmts += [("INSERT INTO skill_files (skill, path, content) VALUES (?,?,?)", [name, p, c])
|
| 251 |
+
for p, c in files.items()]
|
| 252 |
+
for i in range(0, len(stmts), 50):
|
| 253 |
+
await db.batch(stmts[i:i + 50])
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
async def get_skill_files(name: str):
|
| 257 |
+
return (await db.execute("SELECT path, content FROM skill_files WHERE skill = ? ORDER BY path", [name]))["rows"]
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
async def all_skill_files():
|
| 261 |
+
return (await db.execute("SELECT skill, path, content FROM skill_files"))["rows"]
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
async def set_skill_enabled(name: str, enabled: bool):
|
| 265 |
+
await db.execute("UPDATE skills SET enabled = ? WHERE name = ?", [1 if enabled else 0, name])
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
async def delete_skill(name: str):
|
| 269 |
+
await db.batch([("DELETE FROM skill_files WHERE skill = ?", [name]),
|
| 270 |
+
("DELETE FROM skills WHERE name = ?", [name])])
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
# ---------- 專案 ----------
|
| 274 |
+
async def create_project(name: str, instructions: str = "") -> str:
|
| 275 |
+
pid, t = uuid.uuid4().hex[:12], now_ms()
|
| 276 |
+
await db.execute("INSERT INTO projects (id, name, instructions, created_at, updated_at) VALUES (?,?,?,?,?)",
|
| 277 |
+
[pid, name or "未命名專案", instructions or "", t, t])
|
| 278 |
+
return pid
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
async def list_projects():
|
| 282 |
+
return (await db.execute("SELECT id, name, instructions, updated_at FROM projects ORDER BY updated_at DESC"))["rows"]
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
async def get_project(pid: str):
|
| 286 |
+
rows = (await db.execute("SELECT * FROM projects WHERE id = ?", [pid]))["rows"]
|
| 287 |
+
return rows[0] if rows else None
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
async def update_project(pid: str, name: str | None = None, instructions: str | None = None):
|
| 291 |
+
if name is not None:
|
| 292 |
+
await db.execute("UPDATE projects SET name = ? WHERE id = ?", [name, pid])
|
| 293 |
+
if instructions is not None:
|
| 294 |
+
await db.execute("UPDATE projects SET instructions = ? WHERE id = ?", [instructions, pid])
|
| 295 |
+
await touch_project(pid)
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
async def touch_project(pid: str):
|
| 299 |
+
await db.execute("UPDATE projects SET updated_at = ? WHERE id = ?", [now_ms(), pid])
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
async def delete_project(pid: str):
|
| 303 |
+
"""刪除專案和它的檔案;專案裡的對話保留,變成未歸類。"""
|
| 304 |
+
await db.batch([("DELETE FROM project_files WHERE project_id = ?", [pid]),
|
| 305 |
+
("UPDATE conversations SET project_id = NULL WHERE project_id = ?", [pid]),
|
| 306 |
+
("DELETE FROM projects WHERE id = ?", [pid])])
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
async def list_project_files(pid: str, with_data: bool = False):
|
| 310 |
+
cols = "path, size, updated_at" + (", data" if with_data else "")
|
| 311 |
+
return (await db.execute(f"SELECT {cols} FROM project_files WHERE project_id = ? ORDER BY path", [pid]))["rows"]
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
def upsert_file_stmt(pid: str, path: str, data_b64: str, size: int):
|
| 315 |
+
return ("INSERT INTO project_files (project_id, path, data, size, updated_at) VALUES (?,?,?,?,?) "
|
| 316 |
+
"ON CONFLICT(project_id, path) DO UPDATE SET data = excluded.data, size = excluded.size, "
|
| 317 |
+
"updated_at = excluded.updated_at", [pid, path, data_b64, size, now_ms()])
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
def delete_file_stmt(pid: str, path: str):
|
| 321 |
+
return ("DELETE FROM project_files WHERE project_id = ? AND path = ?", [pid, path])
|
app/main.py
ADDED
|
@@ -0,0 +1,375 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import base64
|
| 2 |
+
import json
|
| 3 |
+
import logging
|
| 4 |
+
from contextlib import asynccontextmanager
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
from fastapi import Depends, FastAPI, HTTPException, Request
|
| 8 |
+
from fastapi.responses import FileResponse, Response, StreamingResponse
|
| 9 |
+
from pydantic import BaseModel
|
| 10 |
+
|
| 11 |
+
from . import auth, config
|
| 12 |
+
from . import db as store
|
| 13 |
+
from . import providers
|
| 14 |
+
from . import skills as skillmod
|
| 15 |
+
from . import workspace
|
| 16 |
+
from .agent import run_agent
|
| 17 |
+
from .mcp_client import manager as mcp
|
| 18 |
+
|
| 19 |
+
log = logging.getLogger("agent")
|
| 20 |
+
STATIC = Path(__file__).parent / "static"
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@asynccontextmanager
|
| 24 |
+
async def lifespan(app: FastAPI):
|
| 25 |
+
missing = [k for k in ("APP_SECRET", "TURSO_DATABASE_URL", "TURSO_AUTH_TOKEN")
|
| 26 |
+
if not getattr(config, k)]
|
| 27 |
+
if missing:
|
| 28 |
+
raise RuntimeError("缺少環境變數(請在 Space Settings → Secrets 設定): " + ", ".join(missing))
|
| 29 |
+
if len(config.APP_SECRET) < 12:
|
| 30 |
+
log.warning("APP_SECRET 太短,建議至少 16 個隨機字元")
|
| 31 |
+
await store.init_schema()
|
| 32 |
+
try:
|
| 33 |
+
await skillmod.sync_all()
|
| 34 |
+
await skillmod.install_defaults()
|
| 35 |
+
except Exception: # noqa: BLE001
|
| 36 |
+
log.exception("技能同步失敗")
|
| 37 |
+
await mcp.reload()
|
| 38 |
+
yield
|
| 39 |
+
await mcp.stop_all()
|
| 40 |
+
await store.db.close()
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
app = FastAPI(lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None)
|
| 44 |
+
AUTH = [Depends(auth.require_auth)]
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class LoginIn(BaseModel):
|
| 48 |
+
secret: str
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class ChatIn(BaseModel):
|
| 52 |
+
message: str
|
| 53 |
+
conversation_id: str | None = None
|
| 54 |
+
model: str | None = None # 提供商id::模型id,可隨時切換
|
| 55 |
+
project_id: str | None = None # 新對話歸屬的專案
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class RenameIn(BaseModel):
|
| 59 |
+
title: str | None = None
|
| 60 |
+
model: str | None = None
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class SettingsIn(BaseModel):
|
| 64 |
+
system_prompt: str | None = None
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class SkillInstallIn(BaseModel):
|
| 68 |
+
source: str | None = None
|
| 69 |
+
content: str | None = None
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
class SkillPatchIn(BaseModel):
|
| 73 |
+
enabled: bool
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
class MCPConfigIn(BaseModel):
|
| 77 |
+
config: str
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class ProvidersIn(BaseModel):
|
| 81 |
+
providers: list[dict]
|
| 82 |
+
selected: str | None = None
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class ModelsQueryIn(BaseModel):
|
| 86 |
+
base_url: str
|
| 87 |
+
api_key: str = ""
|
| 88 |
+
id: str | None = None
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
class ProjectIn(BaseModel):
|
| 92 |
+
name: str | None = None
|
| 93 |
+
instructions: str | None = None
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
class FileUploadIn(BaseModel):
|
| 97 |
+
path: str
|
| 98 |
+
b64: str
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
class MemoryIn(BaseModel):
|
| 102 |
+
content: str
|
| 103 |
+
tags: str = ""
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
@app.get("/")
|
| 107 |
+
async def index():
|
| 108 |
+
return FileResponse(STATIC / "index.html", headers={"Cache-Control": "no-cache"})
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
@app.get("/api/health")
|
| 112 |
+
async def health():
|
| 113 |
+
return {"ok": True}
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
@app.post("/api/login")
|
| 117 |
+
async def login(body: LoginIn, request: Request):
|
| 118 |
+
ip = auth.client_ip(request)
|
| 119 |
+
if auth.is_locked(ip):
|
| 120 |
+
raise HTTPException(429, "嘗試次數過多,請 10 分鐘後再試")
|
| 121 |
+
if not auth.check_secret(body.secret):
|
| 122 |
+
auth.record_fail(ip)
|
| 123 |
+
raise HTTPException(401, "密碼錯誤")
|
| 124 |
+
auth.clear_fails(ip)
|
| 125 |
+
return {"token": auth.issue_token()}
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
@app.get("/api/me", dependencies=AUTH)
|
| 129 |
+
async def me():
|
| 130 |
+
return {"ok": True, "model": await providers.label()}
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
# ---------- 對話 ----------
|
| 134 |
+
@app.get("/api/conversations", dependencies=AUTH)
|
| 135 |
+
async def conversations(project: str = "all"):
|
| 136 |
+
return await store.list_conversations(project)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
@app.get("/api/conversations/{cid}/messages", dependencies=AUTH)
|
| 140 |
+
async def messages(cid: str):
|
| 141 |
+
if not await store.get_conversation(cid):
|
| 142 |
+
raise HTTPException(404, "找不到對話")
|
| 143 |
+
return await store.get_messages(cid)
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
@app.patch("/api/conversations/{cid}", dependencies=AUTH)
|
| 147 |
+
async def rename(cid: str, body: RenameIn):
|
| 148 |
+
if body.title is not None:
|
| 149 |
+
await store.rename_conversation(cid, body.title.strip()[:100] or "新對話")
|
| 150 |
+
if body.model is not None:
|
| 151 |
+
await store.set_conversation_model(cid, body.model)
|
| 152 |
+
return {"ok": True}
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
@app.delete("/api/conversations/{cid}", dependencies=AUTH)
|
| 156 |
+
async def delete(cid: str):
|
| 157 |
+
await store.delete_conversation(cid)
|
| 158 |
+
return {"ok": True}
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def sse(obj) -> str:
|
| 162 |
+
return f"data: {json.dumps(obj, ensure_ascii=False)}\n\n"
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
@app.post("/api/chat", dependencies=AUTH)
|
| 166 |
+
async def chat(body: ChatIn):
|
| 167 |
+
text = body.message.strip()
|
| 168 |
+
if not text:
|
| 169 |
+
raise HTTPException(400, "訊息是空的")
|
| 170 |
+
cid = body.conversation_id
|
| 171 |
+
conv = await store.get_conversation(cid) if cid else None
|
| 172 |
+
if not conv:
|
| 173 |
+
pid = body.project_id if body.project_id and await store.get_project(body.project_id) else None
|
| 174 |
+
cid = await store.create_conversation(text.replace("\n", " ")[:40], pid)
|
| 175 |
+
conv = {}
|
| 176 |
+
model = body.model or conv.get("model")
|
| 177 |
+
if body.model and body.model != conv.get("model"):
|
| 178 |
+
await store.set_conversation_model(cid, body.model)
|
| 179 |
+
|
| 180 |
+
async def gen():
|
| 181 |
+
yield sse({"type": "conversation", "id": cid})
|
| 182 |
+
try:
|
| 183 |
+
async for ev in run_agent(cid, text, model):
|
| 184 |
+
yield sse(ev)
|
| 185 |
+
except Exception as e: # noqa: BLE001
|
| 186 |
+
log.exception("agent error")
|
| 187 |
+
yield sse({"type": "error", "message": f"{type(e).__name__}: {e}"})
|
| 188 |
+
|
| 189 |
+
return StreamingResponse(gen(), media_type="text/event-stream",
|
| 190 |
+
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"})
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
# ---------- 設定 ----------
|
| 194 |
+
@app.get("/api/settings", dependencies=AUTH)
|
| 195 |
+
async def get_settings():
|
| 196 |
+
return {
|
| 197 |
+
"system_prompt": await store.get_setting("system_prompt") or "",
|
| 198 |
+
"default_system_prompt": config.DEFAULT_SYSTEM_PROMPT,
|
| 199 |
+
}
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
@app.put("/api/settings", dependencies=AUTH)
|
| 203 |
+
async def put_settings(body: SettingsIn):
|
| 204 |
+
if body.system_prompt is not None:
|
| 205 |
+
await store.set_setting("system_prompt", body.system_prompt.strip())
|
| 206 |
+
return {"ok": True}
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
# ---------- 模型提供商 ----------
|
| 210 |
+
@app.get("/api/providers", dependencies=AUTH)
|
| 211 |
+
async def get_providers():
|
| 212 |
+
return await providers.public()
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
@app.put("/api/providers", dependencies=AUTH)
|
| 216 |
+
async def put_providers(body: ProvidersIn):
|
| 217 |
+
await providers.save(body.providers, body.selected)
|
| 218 |
+
return await providers.public()
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
@app.post("/api/providers/models", dependencies=AUTH)
|
| 222 |
+
async def provider_models(body: ModelsQueryIn):
|
| 223 |
+
try:
|
| 224 |
+
return {"models": await providers.list_models(body.base_url, body.api_key, body.id)}
|
| 225 |
+
except Exception as e: # noqa: BLE001
|
| 226 |
+
raise HTTPException(400, f"取得模型清單失敗: {e}")
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
# ---------- 記憶 ----------
|
| 230 |
+
@app.get("/api/memories", dependencies=AUTH)
|
| 231 |
+
async def memories():
|
| 232 |
+
return await store.recent_memories(500)
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
@app.post("/api/memories", dependencies=AUTH)
|
| 236 |
+
async def add_memory(body: MemoryIn):
|
| 237 |
+
if not body.content.strip():
|
| 238 |
+
raise HTTPException(400, "內容是空的")
|
| 239 |
+
return {"id": await store.add_memory(body.content.strip(), body.tags)}
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
@app.delete("/api/memories/{mid}", dependencies=AUTH)
|
| 243 |
+
async def del_memory(mid: int):
|
| 244 |
+
await store.delete_memory(mid)
|
| 245 |
+
return {"ok": True}
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
# ---------- 技能 ----------
|
| 249 |
+
@app.get("/api/skills", dependencies=AUTH)
|
| 250 |
+
async def list_skills():
|
| 251 |
+
return await store.list_skills()
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
@app.post("/api/skills/install", dependencies=AUTH)
|
| 255 |
+
async def install_skill(body: SkillInstallIn):
|
| 256 |
+
try:
|
| 257 |
+
return await skillmod.install(source=body.source, content=body.content)
|
| 258 |
+
except Exception as e: # noqa: BLE001
|
| 259 |
+
raise HTTPException(400, f"安裝失敗: {e}")
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
@app.patch("/api/skills/{name}", dependencies=AUTH)
|
| 263 |
+
async def patch_skill(name: str, body: SkillPatchIn):
|
| 264 |
+
await store.set_skill_enabled(name, body.enabled)
|
| 265 |
+
return {"ok": True}
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
@app.delete("/api/skills/{name}", dependencies=AUTH)
|
| 269 |
+
async def delete_skill(name: str):
|
| 270 |
+
await store.delete_skill(name)
|
| 271 |
+
return {"ok": True}
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
# ---------- MCP ----------
|
| 275 |
+
@app.get("/api/mcp", dependencies=AUTH)
|
| 276 |
+
async def get_mcp():
|
| 277 |
+
cfg = await mcp.get_config()
|
| 278 |
+
return {"config": json.dumps(cfg, ensure_ascii=False, indent=2), "status": mcp.status()}
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
@app.put("/api/mcp", dependencies=AUTH)
|
| 282 |
+
async def put_mcp(body: MCPConfigIn):
|
| 283 |
+
try:
|
| 284 |
+
cfg = json.loads(body.config or "{}")
|
| 285 |
+
assert isinstance(cfg, dict) and isinstance(cfg.get("mcpServers", {}), dict)
|
| 286 |
+
except Exception: # noqa: BLE001
|
| 287 |
+
raise HTTPException(400, '格式錯誤,需要 {"mcpServers": {...}}')
|
| 288 |
+
cfg.setdefault("mcpServers", {})
|
| 289 |
+
await store.set_setting("mcp_config", json.dumps(cfg, ensure_ascii=False))
|
| 290 |
+
await mcp.reload()
|
| 291 |
+
return {"status": mcp.status()}
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
@app.post("/api/mcp/reload", dependencies=AUTH)
|
| 295 |
+
async def reload_mcp():
|
| 296 |
+
await mcp.reload()
|
| 297 |
+
return {"status": mcp.status()}
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
# ---------- 專案 ----------
|
| 301 |
+
async def _project_or_404(pid: str):
|
| 302 |
+
p = await store.get_project(pid)
|
| 303 |
+
if not p:
|
| 304 |
+
raise HTTPException(404, "專案不存在")
|
| 305 |
+
return p
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
@app.get("/api/projects", dependencies=AUTH)
|
| 309 |
+
async def list_projects():
|
| 310 |
+
return await store.list_projects()
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
@app.post("/api/projects", dependencies=AUTH)
|
| 314 |
+
async def create_project(body: ProjectIn):
|
| 315 |
+
pid = await store.create_project((body.name or "").strip()[:80], body.instructions or "")
|
| 316 |
+
return await store.get_project(pid)
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
@app.patch("/api/projects/{pid}", dependencies=AUTH)
|
| 320 |
+
async def update_project(pid: str, body: ProjectIn):
|
| 321 |
+
await _project_or_404(pid)
|
| 322 |
+
await store.update_project(pid, body.name.strip()[:80] if body.name is not None else None, body.instructions)
|
| 323 |
+
return await store.get_project(pid)
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
@app.delete("/api/projects/{pid}", dependencies=AUTH)
|
| 327 |
+
async def delete_project(pid: str):
|
| 328 |
+
await store.delete_project(pid)
|
| 329 |
+
workspace.forget(pid)
|
| 330 |
+
return {"ok": True}
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
@app.get("/api/projects/{pid}/files", dependencies=AUTH)
|
| 334 |
+
async def project_files(pid: str):
|
| 335 |
+
await _project_or_404(pid)
|
| 336 |
+
return await store.list_project_files(pid)
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
@app.post("/api/projects/{pid}/files", dependencies=AUTH)
|
| 340 |
+
async def upload_file(pid: str, body: FileUploadIn):
|
| 341 |
+
await _project_or_404(pid)
|
| 342 |
+
try:
|
| 343 |
+
data = base64.b64decode(body.b64)
|
| 344 |
+
except Exception: # noqa: BLE001
|
| 345 |
+
raise HTTPException(400, "檔案內容不是合法 base64")
|
| 346 |
+
if len(data) > config.PROJECT_MAX_FILE_MB * 1024 * 1024:
|
| 347 |
+
raise HTTPException(400, f"單檔上限 {config.PROJECT_MAX_FILE_MB}MB")
|
| 348 |
+
try:
|
| 349 |
+
await workspace.write_upload(pid, body.path, data)
|
| 350 |
+
except ValueError as e:
|
| 351 |
+
raise HTTPException(400, str(e))
|
| 352 |
+
return {"ok": True}
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
@app.get("/api/projects/{pid}/file", dependencies=AUTH)
|
| 356 |
+
async def download_file(pid: str, path: str):
|
| 357 |
+
await _project_or_404(pid)
|
| 358 |
+
try:
|
| 359 |
+
data = await workspace.read_bytes(pid, path)
|
| 360 |
+
except (ValueError, OSError):
|
| 361 |
+
raise HTTPException(404, "檔案不存在")
|
| 362 |
+
return Response(data, media_type="application/octet-stream")
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
@app.delete("/api/projects/{pid}/file", dependencies=AUTH)
|
| 366 |
+
async def delete_file(pid: str, path: str):
|
| 367 |
+
await _project_or_404(pid)
|
| 368 |
+
await workspace.delete_path(pid, path)
|
| 369 |
+
return {"ok": True}
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
@app.get("/api/projects/{pid}/zip", dependencies=AUTH)
|
| 373 |
+
async def zip_project(pid: str):
|
| 374 |
+
await _project_or_404(pid)
|
| 375 |
+
return Response(await workspace.zip_project(pid), media_type="application/zip")
|
app/mcp_client.py
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""MCP 客戶端:連接外部 MCP 伺服器,把它們的工具自動暴露給 agent。
|
| 2 |
+
|
| 3 |
+
設定格式與 Claude Desktop / Cursor 相同(在前端「🔌 MCP」裡編輯,存在 Turso):
|
| 4 |
+
{
|
| 5 |
+
"mcpServers": {
|
| 6 |
+
"remote-http": {"url": "https://example.com/mcp", "headers": {"Authorization": "Bearer ${MY_TOKEN}"}},
|
| 7 |
+
"remote-sse": {"url": "https://example.com/sse", "transport": "sse"},
|
| 8 |
+
"local-stdio": {"command": "npx", "args": ["-y", "@modelcontextprotocol/server-everything"], "env": {}}
|
| 9 |
+
}
|
| 10 |
+
}
|
| 11 |
+
字串裡的 ${VAR} 會替換成 Space Secrets 裡同名的環境變數,key 不用寫進資料庫。
|
| 12 |
+
"""
|
| 13 |
+
import asyncio
|
| 14 |
+
import json
|
| 15 |
+
import logging
|
| 16 |
+
import os
|
| 17 |
+
import re
|
| 18 |
+
from contextlib import AsyncExitStack
|
| 19 |
+
|
| 20 |
+
from mcp import ClientSession, StdioServerParameters
|
| 21 |
+
from mcp.client.sse import sse_client
|
| 22 |
+
from mcp.client.stdio import stdio_client
|
| 23 |
+
from mcp.client.streamable_http import streamablehttp_client
|
| 24 |
+
|
| 25 |
+
from . import config
|
| 26 |
+
from . import db as store
|
| 27 |
+
|
| 28 |
+
log = logging.getLogger("mcp")
|
| 29 |
+
DEFAULT_CONFIG = {"mcpServers": {}}
|
| 30 |
+
_VAR = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}")
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _subst(v):
|
| 34 |
+
if isinstance(v, str):
|
| 35 |
+
return _VAR.sub(lambda m: os.environ.get(m.group(1), ""), v)
|
| 36 |
+
if isinstance(v, list):
|
| 37 |
+
return [_subst(x) for x in v]
|
| 38 |
+
if isinstance(v, dict):
|
| 39 |
+
return {k: _subst(x) for k, x in v.items()}
|
| 40 |
+
return v
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class MCPConn:
|
| 44 |
+
def __init__(self, name: str, cfg: dict):
|
| 45 |
+
self.name, self.cfg = name, _subst(cfg)
|
| 46 |
+
self.session: ClientSession | None = None
|
| 47 |
+
self.tools: list = []
|
| 48 |
+
self.error: str | None = None
|
| 49 |
+
self.ready, self.stop = asyncio.Event(), asyncio.Event()
|
| 50 |
+
self.task: asyncio.Task | None = None
|
| 51 |
+
|
| 52 |
+
async def start(self):
|
| 53 |
+
self.task = asyncio.create_task(self._run())
|
| 54 |
+
try:
|
| 55 |
+
await asyncio.wait_for(self.ready.wait(), config.MCP_CONNECT_TIMEOUT)
|
| 56 |
+
except asyncio.TimeoutError:
|
| 57 |
+
self.error = f"連線逾時({config.MCP_CONNECT_TIMEOUT}s)"
|
| 58 |
+
self.stop.set()
|
| 59 |
+
|
| 60 |
+
async def _run(self):
|
| 61 |
+
c = self.cfg
|
| 62 |
+
try:
|
| 63 |
+
async with AsyncExitStack() as stack:
|
| 64 |
+
if c.get("command"):
|
| 65 |
+
env = {"PATH": os.environ.get("PATH", ""), "HOME": os.environ.get("HOME", "/tmp"),
|
| 66 |
+
"LANG": "C.UTF-8", **{k: str(v) for k, v in (c.get("env") or {}).items()}}
|
| 67 |
+
params = StdioServerParameters(command=c["command"], args=c.get("args") or [],
|
| 68 |
+
env=env, cwd=c.get("cwd"))
|
| 69 |
+
read, write = await stack.enter_async_context(stdio_client(params))
|
| 70 |
+
elif c.get("url"):
|
| 71 |
+
# 去掉替換後變空的 header(例如 Secret 沒設定)
|
| 72 |
+
headers = {k: str(v).strip() for k, v in (c.get("headers") or {}).items()
|
| 73 |
+
if str(v).strip() and str(v).strip().lower() not in ("bearer", "token")}
|
| 74 |
+
transport = (c.get("transport") or c.get("type") or "").lower()
|
| 75 |
+
if transport == "sse" or (not transport and c["url"].rstrip("/").endswith("/sse")):
|
| 76 |
+
read, write = await stack.enter_async_context(sse_client(c["url"], headers=headers))
|
| 77 |
+
else:
|
| 78 |
+
read, write, _ = await stack.enter_async_context(
|
| 79 |
+
streamablehttp_client(c["url"], headers=headers))
|
| 80 |
+
else:
|
| 81 |
+
raise ValueError("需要 command(stdio)或 url(http/sse)")
|
| 82 |
+
session = await stack.enter_async_context(ClientSession(read, write))
|
| 83 |
+
await session.initialize()
|
| 84 |
+
self.tools = (await session.list_tools()).tools
|
| 85 |
+
self.session = session
|
| 86 |
+
self.ready.set()
|
| 87 |
+
await self.stop.wait()
|
| 88 |
+
except Exception as e: # noqa: BLE001
|
| 89 |
+
msg = repr(e)
|
| 90 |
+
if hasattr(e, "exceptions"): # ExceptionGroup
|
| 91 |
+
msg = "; ".join(repr(x) for x in e.exceptions)
|
| 92 |
+
self.error = msg[:500]
|
| 93 |
+
log.warning("MCP %s 失敗: %s", self.name, self.error)
|
| 94 |
+
finally:
|
| 95 |
+
self.session = None
|
| 96 |
+
self.ready.set()
|
| 97 |
+
|
| 98 |
+
async def close(self):
|
| 99 |
+
self.stop.set()
|
| 100 |
+
if self.task:
|
| 101 |
+
try:
|
| 102 |
+
await asyncio.wait_for(self.task, 10)
|
| 103 |
+
except Exception: # noqa: BLE001
|
| 104 |
+
self.task.cancel()
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def _convert(res) -> dict:
|
| 108 |
+
parts = []
|
| 109 |
+
for item in res.content or []:
|
| 110 |
+
t = getattr(item, "type", "")
|
| 111 |
+
if t == "text":
|
| 112 |
+
parts.append(item.text)
|
| 113 |
+
elif t == "image":
|
| 114 |
+
parts.append(f"[圖片 {getattr(item, 'mimeType', '')}]")
|
| 115 |
+
elif t == "resource":
|
| 116 |
+
r = item.resource
|
| 117 |
+
parts.append(getattr(r, "text", None) or f"[資源 {getattr(r, 'uri', '')}]")
|
| 118 |
+
else:
|
| 119 |
+
parts.append(str(item))
|
| 120 |
+
out = {"content": "\n".join(parts)}
|
| 121 |
+
if not parts and getattr(res, "structuredContent", None):
|
| 122 |
+
out["content"] = json.dumps(res.structuredContent, ensure_ascii=False)
|
| 123 |
+
if getattr(res, "isError", False):
|
| 124 |
+
out["is_error"] = True
|
| 125 |
+
return out
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
class MCPManager:
|
| 129 |
+
def __init__(self):
|
| 130 |
+
self.conns: dict[str, MCPConn] = {}
|
| 131 |
+
self.tool_map: dict[str, tuple[MCPConn, str]] = {}
|
| 132 |
+
self.schemas: list[dict] = []
|
| 133 |
+
self.lock = asyncio.Lock()
|
| 134 |
+
|
| 135 |
+
async def get_config(self) -> dict:
|
| 136 |
+
raw = await store.get_setting("mcp_config")
|
| 137 |
+
try:
|
| 138 |
+
cfg = json.loads(raw) if raw else DEFAULT_CONFIG
|
| 139 |
+
except json.JSONDecodeError:
|
| 140 |
+
cfg = DEFAULT_CONFIG
|
| 141 |
+
return cfg if isinstance(cfg, dict) else DEFAULT_CONFIG
|
| 142 |
+
|
| 143 |
+
async def reload(self):
|
| 144 |
+
async with self.lock:
|
| 145 |
+
await self.stop_all()
|
| 146 |
+
servers = (await self.get_config()).get("mcpServers") or {}
|
| 147 |
+
conns = [MCPConn(n, c) for n, c in servers.items() if isinstance(c, dict) and not c.get("disabled")]
|
| 148 |
+
await asyncio.gather(*(c.start() for c in conns))
|
| 149 |
+
self.conns = {c.name: c for c in conns}
|
| 150 |
+
self._rebuild()
|
| 151 |
+
|
| 152 |
+
def _rebuild(self):
|
| 153 |
+
self.tool_map, self.schemas = {}, []
|
| 154 |
+
for c in self.conns.values():
|
| 155 |
+
if not c.session:
|
| 156 |
+
continue
|
| 157 |
+
for t in c.tools:
|
| 158 |
+
base = re.sub(r"[^a-zA-Z0-9_-]", "_", f"mcp_{c.name}_{t.name}")[:64]
|
| 159 |
+
fname, i = base, 2
|
| 160 |
+
while fname in self.tool_map:
|
| 161 |
+
fname, i = f"{base[:60]}_{i}", i + 1
|
| 162 |
+
self.tool_map[fname] = (c, t.name)
|
| 163 |
+
schema = t.inputSchema or {}
|
| 164 |
+
if schema.get("type") != "object":
|
| 165 |
+
schema = {"type": "object", "properties": {}}
|
| 166 |
+
self.schemas.append({"type": "function", "function": {
|
| 167 |
+
"name": fname,
|
| 168 |
+
"description": f"[MCP:{c.name}] {(t.description or t.name)[:1000]}",
|
| 169 |
+
"parameters": schema}})
|
| 170 |
+
|
| 171 |
+
async def call(self, fname: str, args: dict) -> dict:
|
| 172 |
+
conn, tname = self.tool_map[fname]
|
| 173 |
+
if not conn.session:
|
| 174 |
+
return {"error": f"MCP 伺服器 {conn.name} 已斷線,請在 MCP 設定裡重新連線"}
|
| 175 |
+
res = await asyncio.wait_for(conn.session.call_tool(tname, args), config.MCP_CALL_TIMEOUT)
|
| 176 |
+
return _convert(res)
|
| 177 |
+
|
| 178 |
+
def status(self) -> list[dict]:
|
| 179 |
+
return [{"name": c.name, "connected": c.session is not None, "error": c.error,
|
| 180 |
+
"tools": [t.name for t in c.tools] if c.session else []}
|
| 181 |
+
for c in self.conns.values()]
|
| 182 |
+
|
| 183 |
+
async def stop_all(self):
|
| 184 |
+
await asyncio.gather(*(c.close() for c in self.conns.values()), return_exceptions=True)
|
| 185 |
+
self.conns, self.tool_map, self.schemas = {}, {}, []
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
manager = MCPManager()
|
app/providers.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""模型提供商:在前端「🤖 模型」面板裡新增,數量不限,存在 Turso。
|
| 2 |
+
|
| 3 |
+
每個提供商 = 一個 OpenAI 相容端點 + key + 你挑選的模型清單。
|
| 4 |
+
只用你手動選的模型,不自動切換、不預設模型。
|
| 5 |
+
key 可以直接填,也可以填 ${VAR} 從 Space Secrets 讀。
|
| 6 |
+
"""
|
| 7 |
+
import json
|
| 8 |
+
import os
|
| 9 |
+
import re
|
| 10 |
+
import uuid
|
| 11 |
+
|
| 12 |
+
import httpx
|
| 13 |
+
|
| 14 |
+
from . import db as store
|
| 15 |
+
|
| 16 |
+
SEP = "::" # 選定模型的格式:提供商id::模型id
|
| 17 |
+
MASK = "••••"
|
| 18 |
+
_VAR = re.compile(r"^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$")
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _resolve_key(k: str) -> str:
|
| 22 |
+
m = _VAR.match((k or "").strip())
|
| 23 |
+
return os.environ.get(m.group(1), "") if m else (k or "")
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _mask(k: str) -> str:
|
| 27 |
+
if not k:
|
| 28 |
+
return ""
|
| 29 |
+
if _VAR.match(k.strip()):
|
| 30 |
+
return k # ${VAR} 不是秘密,照原樣顯示
|
| 31 |
+
return MASK + k[-4:]
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
async def _stored() -> list[dict]:
|
| 35 |
+
raw = await store.get_setting("providers")
|
| 36 |
+
try:
|
| 37 |
+
data = json.loads(raw) if raw else []
|
| 38 |
+
except json.JSONDecodeError:
|
| 39 |
+
data = []
|
| 40 |
+
return data if isinstance(data, list) else []
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
async def get_all() -> list[dict]:
|
| 44 |
+
"""所有提供商(含真實 key)。"""
|
| 45 |
+
return [p for p in await _stored() if isinstance(p, dict)]
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
async def public() -> dict:
|
| 49 |
+
ps = [{**p, "api_key": _mask(p.get("api_key", ""))} for p in await get_all()]
|
| 50 |
+
return {"providers": ps,
|
| 51 |
+
"selected": await store.get_setting("model") or ""}
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
async def save(providers: list[dict], selected: str | None):
|
| 55 |
+
old = {p.get("id"): p for p in await _stored()}
|
| 56 |
+
out = []
|
| 57 |
+
for p in providers:
|
| 58 |
+
pid = p.get("id") or uuid.uuid4().hex[:8]
|
| 59 |
+
key = (p.get("api_key") or "").strip()
|
| 60 |
+
if key.startswith(MASK): # 沒改 key → 沿用舊的
|
| 61 |
+
key = old.get(pid, {}).get("api_key", "")
|
| 62 |
+
models = p.get("models") or []
|
| 63 |
+
if isinstance(models, str):
|
| 64 |
+
models = models.split(",")
|
| 65 |
+
out.append({"id": pid, "name": (p.get("name") or "未命名").strip()[:60],
|
| 66 |
+
"base_url": (p.get("base_url") or "").strip().rstrip("/"),
|
| 67 |
+
"api_key": key, "models": [m.strip() for m in models if m.strip()],
|
| 68 |
+
"available": [str(m) for m in (p.get("available") or [])][:5000], # 上次拉取的完整清單
|
| 69 |
+
"enabled": bool(p.get("enabled", True))})
|
| 70 |
+
await store.set_setting("providers", json.dumps(out, ensure_ascii=False))
|
| 71 |
+
if selected is not None:
|
| 72 |
+
await store.set_setting("model", selected)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
async def resolve(selected: str | None = None) -> tuple[dict, str] | None:
|
| 76 |
+
"""找出要用的 (提供商, 模型):對話自己的選擇優先,其次是全域選擇。找不到就回 None,不會自己挑。"""
|
| 77 |
+
for sel in (selected, await store.get_setting("model")):
|
| 78 |
+
if sel and SEP in sel:
|
| 79 |
+
pid, model = sel.split(SEP, 1)
|
| 80 |
+
for p in await get_all():
|
| 81 |
+
if p.get("id") == pid and p.get("enabled", True) and model in (p.get("models") or []):
|
| 82 |
+
return p, model
|
| 83 |
+
return None
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def key_of(p: dict) -> str:
|
| 87 |
+
return _resolve_key(p.get("api_key", ""))
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
async def label() -> str:
|
| 91 |
+
r = await resolve()
|
| 92 |
+
return f"{r[0]['name']} · {r[1]}" if r else "尚未選擇模型"
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
async def list_models(base_url: str, api_key: str, pid: str | None = None) -> list[str]:
|
| 96 |
+
if api_key.startswith(MASK) and pid:
|
| 97 |
+
api_key = next((p.get("api_key", "") for p in await get_all() if p.get("id") == pid), "")
|
| 98 |
+
async with httpx.AsyncClient(timeout=30) as c:
|
| 99 |
+
r = await c.get(base_url.rstrip("/") + "/models",
|
| 100 |
+
headers={"Authorization": f"Bearer {_resolve_key(api_key)}"})
|
| 101 |
+
r.raise_for_status()
|
| 102 |
+
data = r.json()
|
| 103 |
+
items = data.get("data", data) if isinstance(data, dict) else data
|
| 104 |
+
ids = [str(m.get("id")) for m in items if isinstance(m, dict) and m.get("id")]
|
| 105 |
+
return sorted({i.removeprefix("models/") for i in ids})
|
app/skills.py
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Skills:相容 Anthropic Agent Skills 格式(資料夾 + SKILL.md,含 YAML frontmatter 的 name / description)。
|
| 2 |
+
|
| 3 |
+
- 存在 Turso(skills / skill_files),啟動時同步到 SKILLS_DIR,讓腳本能用 run_shell / run_python 執行
|
| 4 |
+
- 漸進式載入:系統提示只列出名稱 + 描述,agent 需要時用 load_skill 讀完整說明
|
| 5 |
+
- 安裝來源:GitHub 資料夾網址、SKILL.md 網址、或直接貼上 SKILL.md 內容
|
| 6 |
+
"""
|
| 7 |
+
import io
|
| 8 |
+
import json
|
| 9 |
+
import logging
|
| 10 |
+
import posixpath
|
| 11 |
+
import re
|
| 12 |
+
import shutil
|
| 13 |
+
import tarfile
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
|
| 16 |
+
import httpx
|
| 17 |
+
import yaml
|
| 18 |
+
|
| 19 |
+
from . import config
|
| 20 |
+
from . import db as store
|
| 21 |
+
|
| 22 |
+
log = logging.getLogger("skills")
|
| 23 |
+
MAX_FILES, MAX_FILE_BYTES, MAX_TOTAL, MAX_ARCHIVE = 200, 1_000_000, 5_000_000, 200_000_000
|
| 24 |
+
GH = re.compile(r"^https?://github\.com/([^/]+)/([^/#?]+)(?:/(tree|blob)/([^/]+)(?:/([^#?]*))?)?")
|
| 25 |
+
_tar_cache: dict[str, bytes] = {}
|
| 26 |
+
_batch = False
|
| 27 |
+
RAW = re.compile(r"^https?://raw\.githubusercontent\.com/([^/]+)/([^/]+)/([^/]+)/(.+)$")
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def parse_frontmatter(text: str) -> tuple[dict, str]:
|
| 31 |
+
m = re.match(r"^\ufeff?---\s*\n(.*?)\n---\s*(?:\n|$)(.*)$", text, re.S)
|
| 32 |
+
if not m:
|
| 33 |
+
return {}, text
|
| 34 |
+
try:
|
| 35 |
+
meta = yaml.safe_load(m.group(1)) or {}
|
| 36 |
+
except yaml.YAMLError:
|
| 37 |
+
meta = {}
|
| 38 |
+
return (meta if isinstance(meta, dict) else {}), m.group(2)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def slug(s: str) -> str:
|
| 42 |
+
s = re.sub(r"[^a-z0-9_-]+", "-", (s or "").lower()).strip("-")
|
| 43 |
+
return s[:64] or "skill"
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
async def _github_files(owner: str, repo: str, ref: str | None, path: str) -> dict[str, str]:
|
| 47 |
+
"""下載 repo 壓縮包(codeload,不吃 GitHub API 限流),取出指定子資料夾的文字檔。"""
|
| 48 |
+
headers = {"User-Agent": "my-agent"}
|
| 49 |
+
if config.GITHUB_TOKEN: # 私有 repo 需要
|
| 50 |
+
headers["Authorization"] = f"Bearer {config.GITHUB_TOKEN}"
|
| 51 |
+
url = f"https://codeload.github.com/{owner}/{repo}/tar.gz/{ref or 'HEAD'}"
|
| 52 |
+
data = _tar_cache.get(url)
|
| 53 |
+
if data is None:
|
| 54 |
+
async with httpx.AsyncClient(timeout=120, headers=headers, follow_redirects=True) as c:
|
| 55 |
+
r = await c.get(url)
|
| 56 |
+
if r.status_code in (401, 404) and "Authorization" in c.headers:
|
| 57 |
+
del c.headers["Authorization"]
|
| 58 |
+
r = await c.get(url)
|
| 59 |
+
if r.status_code != 200:
|
| 60 |
+
raise RuntimeError(f"下載 GitHub 失敗 {r.status_code}(repo 或分支不存在?)")
|
| 61 |
+
if len(r.content) > MAX_ARCHIVE:
|
| 62 |
+
raise RuntimeError("repo 壓縮包超過 200MB")
|
| 63 |
+
data = r.content
|
| 64 |
+
if _batch:
|
| 65 |
+
_tar_cache[url] = data
|
| 66 |
+
prefix = path.strip("/")
|
| 67 |
+
files: dict[str, str] = {}
|
| 68 |
+
total = 0
|
| 69 |
+
with tarfile.open(fileobj=io.BytesIO(data), mode="r:gz") as tar:
|
| 70 |
+
for m in tar:
|
| 71 |
+
if not m.isfile() or m.size > MAX_FILE_BYTES:
|
| 72 |
+
continue
|
| 73 |
+
rel = m.name.split("/", 1)[1] if "/" in m.name else "" # 去掉頂層 repo-ref/ 目錄
|
| 74 |
+
if prefix:
|
| 75 |
+
if not rel.startswith(prefix + "/"):
|
| 76 |
+
continue
|
| 77 |
+
rel = rel[len(prefix) + 1:]
|
| 78 |
+
if not rel or ".git/" in rel:
|
| 79 |
+
continue
|
| 80 |
+
try:
|
| 81 |
+
txt = tar.extractfile(m).read().decode("utf-8")
|
| 82 |
+
except (UnicodeDecodeError, AttributeError):
|
| 83 |
+
continue # 略過二進位檔
|
| 84 |
+
total += len(txt)
|
| 85 |
+
if total > MAX_TOTAL or len(files) >= MAX_FILES:
|
| 86 |
+
raise RuntimeError("技能太大(檔案數 > 200 或總量 > 5MB),請指定到單一技能資料夾")
|
| 87 |
+
files[rel] = txt
|
| 88 |
+
if not files:
|
| 89 |
+
raise RuntimeError(f"在 {owner}/{repo} 裡找不到路徑 {prefix or '/'}")
|
| 90 |
+
return files
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
async def fetch_source(source: str) -> dict[str, str]:
|
| 94 |
+
source = source.strip()
|
| 95 |
+
m = GH.match(source)
|
| 96 |
+
if m:
|
| 97 |
+
owner, repo, kind, ref, path = m.groups()
|
| 98 |
+
repo = repo.removesuffix(".git")
|
| 99 |
+
path = path or ""
|
| 100 |
+
if kind == "blob" or path.lower().endswith(".md"):
|
| 101 |
+
path = posixpath.dirname(path)
|
| 102 |
+
return await _github_files(owner, repo, ref, path)
|
| 103 |
+
m = RAW.match(source)
|
| 104 |
+
if m:
|
| 105 |
+
owner, repo, ref, path = m.groups()
|
| 106 |
+
return await _github_files(owner, repo, ref, posixpath.dirname(path))
|
| 107 |
+
if source.startswith(("http://", "https://")):
|
| 108 |
+
async with httpx.AsyncClient(timeout=30, follow_redirects=True) as c:
|
| 109 |
+
r = await c.get(source)
|
| 110 |
+
r.raise_for_status()
|
| 111 |
+
return {"SKILL.md": r.text}
|
| 112 |
+
raise ValueError("不支援的來源:請給 GitHub 資料夾網址、SKILL.md 網址,或貼上 SKILL.md 內容")
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def materialize(name: str, files: dict[str, str]):
|
| 116 |
+
root = (Path(config.SKILLS_DIR) / name).resolve()
|
| 117 |
+
shutil.rmtree(root, ignore_errors=True)
|
| 118 |
+
root.mkdir(parents=True, exist_ok=True)
|
| 119 |
+
for rel, content in files.items():
|
| 120 |
+
p = (root / rel).resolve()
|
| 121 |
+
if root not in p.parents and p != root:
|
| 122 |
+
continue # 防路徑穿越
|
| 123 |
+
p.parent.mkdir(parents=True, exist_ok=True)
|
| 124 |
+
p.write_text(content or "", encoding="utf-8")
|
| 125 |
+
if rel.endswith((".sh", ".py")):
|
| 126 |
+
p.chmod(0o755)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
async def install_files(files: dict[str, str], source: str) -> dict:
|
| 130 |
+
key = next((k for k in files if k.lower() == "skill.md"), None)
|
| 131 |
+
if not key:
|
| 132 |
+
raise ValueError("找不到根目錄的 SKILL.md")
|
| 133 |
+
if key != "SKILL.md":
|
| 134 |
+
files["SKILL.md"] = files.pop(key)
|
| 135 |
+
meta, body = parse_frontmatter(files["SKILL.md"])
|
| 136 |
+
first_line = next((ln.strip("# ").strip() for ln in body.splitlines() if ln.strip()), "")
|
| 137 |
+
name = slug(str(meta.get("name") or first_line or "skill"))
|
| 138 |
+
desc = str(meta.get("description") or first_line)[:1024]
|
| 139 |
+
await store.save_skill(name, desc, source, files)
|
| 140 |
+
materialize(name, files)
|
| 141 |
+
return {"name": name, "description": desc, "files": sorted(files)}
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
async def install(source: str | None = None, content: str | None = None) -> dict:
|
| 145 |
+
if content and content.strip():
|
| 146 |
+
return await install_files({"SKILL.md": content}, "pasted")
|
| 147 |
+
if not source:
|
| 148 |
+
raise ValueError("請提供來源網址或 SKILL.md 內容")
|
| 149 |
+
if "\n" in source.strip() or source.strip().startswith("---"):
|
| 150 |
+
return await install_files({"SKILL.md": source}, "pasted")
|
| 151 |
+
return await install_files(await fetch_source(source), source.strip())
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
async def sync_all():
|
| 155 |
+
"""啟動時把資料庫裡的技能寫到磁碟(HF 容器重啟後檔案會消失)。"""
|
| 156 |
+
by_skill: dict[str, dict[str, str]] = {}
|
| 157 |
+
for r in await store.all_skill_files():
|
| 158 |
+
by_skill.setdefault(r["skill"], {})[r["path"]] = r["content"]
|
| 159 |
+
for name, files in by_skill.items():
|
| 160 |
+
materialize(name, files)
|
| 161 |
+
log.info("已同步 %d 個技能到 %s", len(by_skill), config.SKILLS_DIR)
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
async def load(name: str) -> dict:
|
| 165 |
+
files = {r["path"]: r["content"] for r in await store.get_skill_files(name)}
|
| 166 |
+
if not files:
|
| 167 |
+
return {"error": f"找不到技能 {name}"}
|
| 168 |
+
return {
|
| 169 |
+
"name": name,
|
| 170 |
+
"dir": str(Path(config.SKILLS_DIR) / name),
|
| 171 |
+
"instructions": files.get("SKILL.md", ""),
|
| 172 |
+
"other_files": sorted(k for k in files if k != "SKILL.md"),
|
| 173 |
+
"hint": "腳本可用 run_shell 以絕對路徑執行;其他檔案可用 read_skill_file 讀取。",
|
| 174 |
+
}
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
async def read_file(name: str, path: str) -> dict:
|
| 178 |
+
for r in await store.get_skill_files(name):
|
| 179 |
+
if r["path"] == path:
|
| 180 |
+
return {"name": name, "path": path, "content": r["content"][:30000]}
|
| 181 |
+
return {"error": f"技能 {name} 裡沒有 {path}"}
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
async def install_defaults():
|
| 185 |
+
"""首次啟動安裝 DEFAULT_SKILLS;記錄已處理過的來源,刪掉的不會重裝。"""
|
| 186 |
+
global _batch
|
| 187 |
+
if not config.DEFAULT_SKILLS:
|
| 188 |
+
return
|
| 189 |
+
done = set(json.loads(await store.get_setting("default_skills_done") or "[]"))
|
| 190 |
+
todo = [u for u in config.DEFAULT_SKILLS if u not in done]
|
| 191 |
+
if not todo:
|
| 192 |
+
return
|
| 193 |
+
_batch = True
|
| 194 |
+
try:
|
| 195 |
+
for url in todo:
|
| 196 |
+
try:
|
| 197 |
+
r = await install(source=url)
|
| 198 |
+
log.info("已安裝預設技能 %s", r["name"])
|
| 199 |
+
done.add(url)
|
| 200 |
+
except Exception as e: # noqa: BLE001 下次啟動再試
|
| 201 |
+
log.warning("預設技能安裝失敗 %s: %s", url, e)
|
| 202 |
+
finally:
|
| 203 |
+
_batch = False
|
| 204 |
+
_tar_cache.clear()
|
| 205 |
+
await store.set_setting("default_skills_done", json.dumps(sorted(done)))
|
app/static/index.html
ADDED
|
@@ -0,0 +1,601 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!doctype html>
|
| 2 |
+
<html lang="zh-Hant">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="utf-8">
|
| 5 |
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
| 6 |
+
<meta name="robots" content="noindex, nofollow">
|
| 7 |
+
<title>My Agent</title>
|
| 8 |
+
<script src="https://cdn.jsdelivr.net/npm/marked@12/marked.min.js"></script>
|
| 9 |
+
<script src="https://cdn.jsdelivr.net/npm/dompurify@3/dist/purify.min.js"></script>
|
| 10 |
+
<style>
|
| 11 |
+
:root{--bg:#0f1115;--panel:#171a21;--panel2:#1f232c;--line:#2a2f3a;--text:#e6e8ee;--muted:#8b93a7;--accent:#6c8cff;--danger:#ff6b6b}
|
| 12 |
+
*{box-sizing:border-box}
|
| 13 |
+
html,body{margin:0;height:100%;background:var(--bg);color:var(--text);font:15px/1.6 -apple-system,BlinkMacSystemFont,"Segoe UI","PingFang TC","Noto Sans TC","Microsoft JhengHei",sans-serif}
|
| 14 |
+
button{font:inherit;color:inherit;background:var(--panel2);border:1px solid var(--line);border-radius:8px;padding:7px 12px;cursor:pointer}
|
| 15 |
+
button:hover{border-color:var(--accent)}
|
| 16 |
+
button.primary{background:var(--accent);border-color:var(--accent);color:#fff}
|
| 17 |
+
button.ghost{background:transparent;border-color:transparent}
|
| 18 |
+
input,textarea{font:inherit;color:var(--text);background:var(--panel2);border:1px solid var(--line);border-radius:8px;padding:9px 11px;width:100%;outline:none}
|
| 19 |
+
input:focus,textarea:focus{border-color:var(--accent)}
|
| 20 |
+
.hidden{display:none!important}
|
| 21 |
+
#login{position:fixed;inset:0;display:flex;align-items:center;justify-content:center;background:var(--bg);z-index:50}
|
| 22 |
+
#login form{width:min(360px,90vw);background:var(--panel);border:1px solid var(--line);border-radius:14px;padding:28px;display:flex;flex-direction:column;gap:14px}
|
| 23 |
+
#login h1{margin:0;font-size:20px}
|
| 24 |
+
#loginErr{color:var(--danger);min-height:1em;font-size:13px}
|
| 25 |
+
#app{display:flex;height:100%}
|
| 26 |
+
#side{width:270px;background:var(--panel);border-right:1px solid var(--line);display:flex;flex-direction:column}
|
| 27 |
+
#side .top{padding:12px;display:flex;gap:8px}
|
| 28 |
+
#side .top button{flex:1}
|
| 29 |
+
#convs{flex:1;overflow:auto;padding:4px 8px}
|
| 30 |
+
.conv{display:flex;align-items:center;gap:6px;padding:8px 10px;border-radius:8px;cursor:pointer;color:var(--muted)}
|
| 31 |
+
.conv:hover,.conv.active{background:var(--panel2);color:var(--text)}
|
| 32 |
+
.conv .t{flex:1;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
| 33 |
+
.conv .x{opacity:0;padding:0 6px;border:none;background:none}
|
| 34 |
+
.conv:hover .x{opacity:.7}
|
| 35 |
+
#side .bottom{padding:12px;display:flex;flex-wrap:wrap;gap:8px;border-top:1px solid var(--line)}
|
| 36 |
+
#main{flex:1;display:flex;flex-direction:column;min-width:0}
|
| 37 |
+
#bar{display:flex;align-items:center;gap:10px;padding:10px 16px;border-bottom:1px solid var(--line)}
|
| 38 |
+
#bar .title{flex:1;font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
| 39 |
+
#bar .model{color:var(--muted);font-size:13px}
|
| 40 |
+
#menuBtn{display:none}
|
| 41 |
+
#chat{flex:1;overflow:auto;padding:24px 16px}
|
| 42 |
+
.wrap{max-width:820px;margin:0 auto}
|
| 43 |
+
.msg{margin:0 0 22px}
|
| 44 |
+
.msg.user .bubble{background:var(--panel2);border:1px solid var(--line);border-radius:14px;padding:10px 14px;white-space:pre-wrap;margin-left:auto;max-width:85%;width:fit-content}
|
| 45 |
+
.msg.assistant .bubble{padding:2px 2px}
|
| 46 |
+
.bubble p{margin:.4em 0}
|
| 47 |
+
.bubble pre{background:#0a0c10;border:1px solid var(--line);border-radius:8px;padding:12px;overflow:auto}
|
| 48 |
+
.bubble code{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:13px}
|
| 49 |
+
.bubble :not(pre)>code{background:var(--panel2);padding:1px 5px;border-radius:4px}
|
| 50 |
+
.bubble a{color:var(--accent)}
|
| 51 |
+
.bubble table{border-collapse:collapse}.bubble td,.bubble th{border:1px solid var(--line);padding:4px 8px}
|
| 52 |
+
details.tool,details.think{background:var(--panel);border:1px solid var(--line);border-radius:10px;margin:8px 0;font-size:13px}
|
| 53 |
+
details.tool summary,details.think summary{cursor:pointer;padding:7px 12px;color:var(--muted)}
|
| 54 |
+
details.tool pre,details.think pre{margin:0;padding:8px 12px;white-space:pre-wrap;word-break:break-word;max-height:320px;overflow:auto;border-top:1px solid var(--line);color:#c9cfdc;font-size:12px}
|
| 55 |
+
.err{color:var(--danger)}
|
| 56 |
+
.cursor::after{content:"▍";animation:blink 1s steps(1) infinite;color:var(--muted)}
|
| 57 |
+
@keyframes blink{50%{opacity:0}}
|
| 58 |
+
#composer{border-top:1px solid var(--line);padding:12px 16px}
|
| 59 |
+
#composer .wrap{display:flex;gap:10px;align-items:flex-end}
|
| 60 |
+
#input{resize:none;max-height:220px;min-height:44px}
|
| 61 |
+
.empty{color:var(--muted);text-align:center;margin-top:18vh}
|
| 62 |
+
.modal{position:fixed;inset:0;background:rgba(0,0,0,.55);display:flex;align-items:center;justify-content:center;z-index:40}
|
| 63 |
+
.modal .box{width:min(680px,94vw);max-height:88vh;overflow:auto;background:var(--panel);border:1px solid var(--line);border-radius:14px;padding:20px;display:flex;flex-direction:column;gap:12px}
|
| 64 |
+
.modal h2{margin:0;font-size:17px}
|
| 65 |
+
.modal label{font-size:13px;color:var(--muted)}
|
| 66 |
+
.mem{display:flex;gap:8px;align-items:flex-start;padding:8px;border:1px solid var(--line);border-radius:8px}
|
| 67 |
+
.mem .c{flex:1}.mem .id{color:var(--muted);font-size:12px}
|
| 68 |
+
.row{display:flex;gap:8px;justify-content:flex-end}
|
| 69 |
+
@media (max-width:760px){
|
| 70 |
+
#side{position:fixed;inset:0 auto 0 0;z-index:30;transform:translateX(-100%);transition:transform .2s}
|
| 71 |
+
#side.open{transform:none}
|
| 72 |
+
#menuBtn{display:inline-block}
|
| 73 |
+
}
|
| 74 |
+
</style>
|
| 75 |
+
</head>
|
| 76 |
+
<body>
|
| 77 |
+
<div id="login" class="hidden">
|
| 78 |
+
<form id="loginForm">
|
| 79 |
+
<h1>🔒 My Agent</h1>
|
| 80 |
+
<input id="secret" type="password" placeholder="輸入密碼" autocomplete="current-password" autofocus>
|
| 81 |
+
<button class="primary" type="submit">登入</button>
|
| 82 |
+
<div id="loginErr"></div>
|
| 83 |
+
</form>
|
| 84 |
+
</div>
|
| 85 |
+
|
| 86 |
+
<div id="app" class="hidden">
|
| 87 |
+
<aside id="side">
|
| 88 |
+
<div class="top" style="display:flex;flex-direction:column;gap:6px">
|
| 89 |
+
<div style="display:flex;gap:6px"><select id="projSel" style="flex:1" title="專案"></select><button id="projBtn" title="管理專案與檔案">📁</button></div>
|
| 90 |
+
<button class="primary" id="newBtn">+ 新對話</button>
|
| 91 |
+
</div>
|
| 92 |
+
<div id="convs"></div>
|
| 93 |
+
<div class="bottom">
|
| 94 |
+
<button id="provBtn">🤖 模型</button>
|
| 95 |
+
<button id="skillBtn">🧩 技能</button>
|
| 96 |
+
<button id="mcpBtn">🔌 MCP</button>
|
| 97 |
+
<button id="memBtn">🧠 記憶</button>
|
| 98 |
+
<button id="setBtn">⚙️ 設定</button>
|
| 99 |
+
<button id="logoutBtn" class="ghost">登出</button>
|
| 100 |
+
</div>
|
| 101 |
+
</aside>
|
| 102 |
+
<main id="main">
|
| 103 |
+
<div id="bar">
|
| 104 |
+
<button id="menuBtn" class="ghost">☰</button>
|
| 105 |
+
<div class="title" id="title">新對話</div>
|
| 106 |
+
<select id="modelSel" class="model" title="目前模型(失敗會自動切到下一個)"></select>
|
| 107 |
+
</div>
|
| 108 |
+
<div id="chat"><div class="wrap" id="msgs"></div></div>
|
| 109 |
+
<div id="composer"><div class="wrap">
|
| 110 |
+
<textarea id="input" rows="1" placeholder="輸入訊息,Enter 送出,Shift+Enter 換行"></textarea>
|
| 111 |
+
<button class="primary" id="sendBtn">送出</button>
|
| 112 |
+
</div></div>
|
| 113 |
+
</main>
|
| 114 |
+
</div>
|
| 115 |
+
|
| 116 |
+
<div id="setModal" class="modal hidden"><div class="box">
|
| 117 |
+
<h2>設定</h2>
|
| 118 |
+
<label>系統提示詞(留空 = 用預設)</label>
|
| 119 |
+
<textarea id="setPrompt" rows="12"></textarea>
|
| 120 |
+
<div class="row"><button id="setCancel">取消</button><button class="primary" id="setSave">儲存</button></div>
|
| 121 |
+
</div></div>
|
| 122 |
+
|
| 123 |
+
<div id="projModal" class="modal hidden"><div class="box" style="max-width:760px">
|
| 124 |
+
<h2 id="projTitle">專案</h2>
|
| 125 |
+
<label>名稱</label><input id="projName" placeholder="例如 my-api-server">
|
| 126 |
+
<label>專案說明(每個對話的 agent 都會看到:技術棧、規範、目標…)</label>
|
| 127 |
+
<textarea id="projInstr" rows="6" placeholder="例如:FastAPI + PostgreSQL,Python 3.11,測試用 pytest,程式碼註解用中文"></textarea>
|
| 128 |
+
<div id="projFilesBox">
|
| 129 |
+
<label>檔案(存在 Turso,容器重啟也不會丟;node_modules、.git、.venv 等不同步)</label>
|
| 130 |
+
<div style="display:flex;gap:6px;flex-wrap:wrap">
|
| 131 |
+
<button id="projUpFiles">上傳檔案</button><button id="projUpDir">上傳資料夾</button><button id="projZip">下載整個專案 .zip</button>
|
| 132 |
+
<input type="file" id="projFileIn" multiple class="hidden"><input type="file" id="projDirIn" webkitdirectory multiple class="hidden">
|
| 133 |
+
</div>
|
| 134 |
+
<input id="projFlt" placeholder="篩選檔案" style="margin-top:6px">
|
| 135 |
+
<div id="projFiles" style="max-height:260px;overflow:auto;border:1px solid var(--line);border-radius:6px;padding:6px;font-size:13px"></div>
|
| 136 |
+
</div>
|
| 137 |
+
<div id="projMsg" style="font-size:13px;color:var(--muted)"></div>
|
| 138 |
+
<div class="row"><button id="projDel" class="ghost" style="margin-right:auto">刪除專案</button><button id="projClose">關閉</button><button class="primary" id="projSave">儲存</button></div>
|
| 139 |
+
</div></div>
|
| 140 |
+
|
| 141 |
+
<div id="provModal" class="modal hidden"><div class="box" style="max-width:760px">
|
| 142 |
+
<h2>模型提供商</h2>
|
| 143 |
+
<label>任何 OpenAI 相容端點都行,數量不限。填 Base URL 和 key(可直接填,或填 <code>${VAR}</code> 從 Space Secrets 讀),按「拉取模型」後篩選、勾選要用的。對話用哪個模型由你在頂欄手動選。</label>
|
| 144 |
+
<div><button id="provAdd">+ 新增提供商</button></div>
|
| 145 |
+
<div id="provList" style="display:flex;flex-direction:column;gap:10px"></div>
|
| 146 |
+
<div id="provMsg" style="font-size:13px;color:var(--muted)"></div>
|
| 147 |
+
<div class="row"><button id="provClose">取消</button><button class="primary" id="provSave">儲存</button></div>
|
| 148 |
+
</div></div>
|
| 149 |
+
|
| 150 |
+
<div id="skillModal" class="modal hidden"><div class="box">
|
| 151 |
+
<h2>技能(Skills)</h2>
|
| 152 |
+
<label>從 GitHub 資料夾或 SKILL.md 網址安裝(例如 https://github.com/anthropics/skills/tree/main/skills/pdf )</label>
|
| 153 |
+
<div style="display:flex;gap:8px"><input id="skillUrl" placeholder="https://github.com/..."><button class="primary" id="skillInstall">安裝</button></div>
|
| 154 |
+
<details><summary style="cursor:pointer;color:var(--muted);font-size:13px">或直接貼上 SKILL.md</summary>
|
| 155 |
+
<textarea id="skillPaste" rows="8" placeholder="--- name: my-skill description: 什麼時候用這個技能 --- # 說明..."></textarea>
|
| 156 |
+
<div class="row" style="margin-top:8px"><button class="primary" id="skillPasteInstall">安裝貼上的技能</button></div>
|
| 157 |
+
</details>
|
| 158 |
+
<div id="skillMsg" style="font-size:13px;color:var(--muted)"></div>
|
| 159 |
+
<div id="skillList" style="display:flex;flex-direction:column;gap:8px"></div>
|
| 160 |
+
<div class="row"><button id="skillClose">關閉</button></div>
|
| 161 |
+
</div></div>
|
| 162 |
+
|
| 163 |
+
<div id="mcpModal" class="modal hidden"><div class="box">
|
| 164 |
+
<h2>MCP 伺服器</h2>
|
| 165 |
+
<label>與 Claude Desktop 相同的 JSON 格式。<code>${VAR}</code> 會替換成 Space Secrets 裡的同名變數。遠端用 url(預設 Streamable HTTP,加 "transport":"sse" 用 SSE);本地用 command(npx / uvx)。</label>
|
| 166 |
+
<textarea id="mcpConfig" rows="14" spellcheck="false" style="font-family:ui-monospace,Menlo,monospace;font-size:13px"></textarea>
|
| 167 |
+
<div id="mcpStatus" style="display:flex;flex-direction:column;gap:6px;font-size:13px"></div>
|
| 168 |
+
<div class="row"><button id="mcpClose">關閉</button><button id="mcpReload">重新連線</button><button class="primary" id="mcpSave">儲存並連線</button></div>
|
| 169 |
+
</div></div>
|
| 170 |
+
|
| 171 |
+
<div id="memModal" class="modal hidden"><div class="box">
|
| 172 |
+
<h2>長期記憶</h2>
|
| 173 |
+
<div style="display:flex;gap:8px"><input id="memNew" placeholder="手動新增一條記憶"><button class="primary" id="memAdd">新增</button></div>
|
| 174 |
+
<div id="memList" style="display:flex;flex-direction:column;gap:8px"></div>
|
| 175 |
+
<div class="row"><button id="memClose">關閉</button></div>
|
| 176 |
+
</div></div>
|
| 177 |
+
|
| 178 |
+
<script>
|
| 179 |
+
const $ = s => document.querySelector(s);
|
| 180 |
+
const TOKEN_KEY = 'agent_token';
|
| 181 |
+
let token = localStorage.getItem(TOKEN_KEY);
|
| 182 |
+
let currentId = null, controller = null, busy = false;
|
| 183 |
+
|
| 184 |
+
marked.setOptions({ breaks: true, gfm: true });
|
| 185 |
+
const md = t => DOMPurify.sanitize(marked.parse(t || ''));
|
| 186 |
+
const esc = t => (t ?? '').toString().replace(/[&<>"]/g, c => ({'&':'&','<':'<','>':'>','"':'"'}[c]));
|
| 187 |
+
const pretty = s => { try { return JSON.stringify(JSON.parse(s), null, 2); } catch { return s || ''; } };
|
| 188 |
+
|
| 189 |
+
async function api(path, opts = {}) {
|
| 190 |
+
opts.headers = Object.assign({ 'Content-Type': 'application/json' }, opts.headers || {},
|
| 191 |
+
token ? { Authorization: 'Bearer ' + token } : {});
|
| 192 |
+
const r = await fetch(path, opts);
|
| 193 |
+
if (r.status === 401 && path !== '/api/login') { logout(); throw new Error('未授權'); }
|
| 194 |
+
if (!r.ok) { let m = r.statusText; try { m = (await r.json()).detail || m; } catch {} throw new Error(m); }
|
| 195 |
+
return r;
|
| 196 |
+
}
|
| 197 |
+
|
| 198 |
+
// ---------- 登入 ----------
|
| 199 |
+
function showLogin() { $('#app').classList.add('hidden'); $('#login').classList.remove('hidden'); $('#secret').focus(); }
|
| 200 |
+
function logout() { token = null; localStorage.removeItem(TOKEN_KEY); showLogin(); }
|
| 201 |
+
$('#loginForm').onsubmit = async e => {
|
| 202 |
+
e.preventDefault(); $('#loginErr').textContent = '';
|
| 203 |
+
try {
|
| 204 |
+
const r = await api('/api/login', { method: 'POST', body: JSON.stringify({ secret: $('#secret').value }) });
|
| 205 |
+
token = (await r.json()).token; localStorage.setItem(TOKEN_KEY, token); $('#secret').value = ''; boot();
|
| 206 |
+
} catch (err) { $('#loginErr').textContent = err.message; }
|
| 207 |
+
};
|
| 208 |
+
$('#logoutBtn').onclick = logout;
|
| 209 |
+
|
| 210 |
+
async function boot() {
|
| 211 |
+
if (!token) return showLogin();
|
| 212 |
+
try { await api('/api/me'); } catch { return; }
|
| 213 |
+
loadModelSel(); await loadProjects();
|
| 214 |
+
$('#login').classList.add('hidden'); $('#app').classList.remove('hidden');
|
| 215 |
+
await loadConvs(); newChat();
|
| 216 |
+
}
|
| 217 |
+
|
| 218 |
+
// ---------- 對話列表 ----------
|
| 219 |
+
async function loadConvs() {
|
| 220 |
+
const list = await (await api('/api/conversations?project=' + encodeURIComponent(curProject || 'all'))).json();
|
| 221 |
+
const box = $('#convs'); box.innerHTML = '';
|
| 222 |
+
for (const c of list) {
|
| 223 |
+
const d = document.createElement('div');
|
| 224 |
+
d.className = 'conv' + (c.id === currentId ? ' active' : '');
|
| 225 |
+
d.innerHTML = `<span class="t">${esc(c.title)}</span><button class="x" title="刪除">✕</button>`;
|
| 226 |
+
d.onclick = () => openConv(c.id, c.title, c.model);
|
| 227 |
+
if (curProject === 'all' && c.project_id && projMap[c.project_id]) d.querySelector('.t').insertAdjacentHTML('beforebegin', `<span class="id" style="font-size:11px;margin-right:4px">[${esc(projMap[c.project_id].name)}]</span>`);
|
| 228 |
+
d.ondblclick = async () => {
|
| 229 |
+
const t = prompt('重新命名', c.title); if (!t) return;
|
| 230 |
+
await api('/api/conversations/' + c.id, { method: 'PATCH', body: JSON.stringify({ title: t }) });
|
| 231 |
+
if (c.id === currentId) $('#title').textContent = t; loadConvs();
|
| 232 |
+
};
|
| 233 |
+
d.querySelector('.x').onclick = async ev => {
|
| 234 |
+
ev.stopPropagation(); if (!confirm('刪除這個對話?')) return;
|
| 235 |
+
await api('/api/conversations/' + c.id, { method: 'DELETE' });
|
| 236 |
+
if (c.id === currentId) newChat(); loadConvs();
|
| 237 |
+
};
|
| 238 |
+
box.appendChild(d);
|
| 239 |
+
}
|
| 240 |
+
}
|
| 241 |
+
function newChat() {
|
| 242 |
+
if (busy) return; currentId = null; $('#title').textContent = '新對話'; setModelSel(null);
|
| 243 |
+
$('#msgs').innerHTML = `<div class="empty">${isRealProject() ? '在專案「' + esc(projMap[curProject].name) + '」裡開始新對話' : '有什麼可以幫你?'}</div>`;
|
| 244 |
+
document.querySelectorAll('.conv').forEach(e => e.classList.remove('active'));
|
| 245 |
+
$('#side').classList.remove('open'); $('#input').focus();
|
| 246 |
+
}
|
| 247 |
+
$('#newBtn').onclick = newChat;
|
| 248 |
+
$('#menuBtn').onclick = () => $('#side').classList.toggle('open');
|
| 249 |
+
|
| 250 |
+
// ---------- 渲染 ----------
|
| 251 |
+
function addUser(text) {
|
| 252 |
+
const d = document.createElement('div'); d.className = 'msg user';
|
| 253 |
+
d.innerHTML = `<div class="bubble">${esc(text)}</div>`; $('#msgs').appendChild(d);
|
| 254 |
+
}
|
| 255 |
+
function newAssistant() {
|
| 256 |
+
const d = document.createElement('div'); d.className = 'msg assistant';
|
| 257 |
+
const b = document.createElement('div'); b.className = 'bubble'; d.appendChild(b); $('#msgs').appendChild(d);
|
| 258 |
+
return { el: b, seg: null, raw: '', think: null, tools: {} };
|
| 259 |
+
}
|
| 260 |
+
function textSeg(a) {
|
| 261 |
+
if (!a.seg) { a.seg = document.createElement('div'); a.raw = ''; a.el.appendChild(a.seg); }
|
| 262 |
+
return a.seg;
|
| 263 |
+
}
|
| 264 |
+
function toolBlock(a, id, name, args) {
|
| 265 |
+
a.seg = null;
|
| 266 |
+
const d = document.createElement('details'); d.className = 'tool';
|
| 267 |
+
d.innerHTML = `<summary>🔧 ${esc(name)} <span class="st">執行中…</span></summary><pre>${esc(pretty(args))}</pre><pre class="res"></pre>`;
|
| 268 |
+
a.el.appendChild(d); a.tools[id] = d; return d;
|
| 269 |
+
}
|
| 270 |
+
function toolResult(a, id, result) {
|
| 271 |
+
const d = a.tools[id]; if (!d) return;
|
| 272 |
+
d.querySelector('.st').textContent = /"error"/.test(result.slice(0, 40)) ? '⚠️ 失敗' : '✓';
|
| 273 |
+
d.querySelector('.res').textContent = pretty(result);
|
| 274 |
+
}
|
| 275 |
+
const scroll = () => { const c = $('#chat'); if (c.scrollHeight - c.scrollTop - c.clientHeight < 200) c.scrollTop = c.scrollHeight; };
|
| 276 |
+
|
| 277 |
+
async function openConv(id, title, model) {
|
| 278 |
+
if (busy) return; currentId = id; $('#title').textContent = title || ''; setModelSel(model);
|
| 279 |
+
$('#side').classList.remove('open'); loadConvs();
|
| 280 |
+
const rows = await (await api(`/api/conversations/${id}/messages`)).json();
|
| 281 |
+
$('#msgs').innerHTML = ''; let a = null;
|
| 282 |
+
for (const m of rows) {
|
| 283 |
+
if (m.role === 'user') { addUser(m.content); a = null; continue; }
|
| 284 |
+
if (!a) a = newAssistant();
|
| 285 |
+
if (m.role === 'assistant') {
|
| 286 |
+
if (m.content) { const s = textSeg(a); a.raw += m.content; s.innerHTML = md(a.raw); }
|
| 287 |
+
if (m.tool_calls) for (const tc of JSON.parse(m.tool_calls)) toolBlock(a, tc.id, tc.function.name, tc.function.arguments);
|
| 288 |
+
} else if (m.role === 'tool') toolResult(a, m.tool_call_id, m.content || '');
|
| 289 |
+
}
|
| 290 |
+
$('#chat').scrollTop = $('#chat').scrollHeight;
|
| 291 |
+
}
|
| 292 |
+
|
| 293 |
+
// ---------- 送出 / 串流 ----------
|
| 294 |
+
async function send() {
|
| 295 |
+
const text = $('#input').value.trim(); if (!text || busy) return;
|
| 296 |
+
busy = true; $('#input').value = ''; autosize();
|
| 297 |
+
$('#sendBtn').textContent = '停止'; $('#sendBtn').classList.remove('primary');
|
| 298 |
+
if ($('#msgs .empty')) $('#msgs').innerHTML = '';
|
| 299 |
+
addUser(text); const a = newAssistant(); a.el.classList.add('cursor'); scroll();
|
| 300 |
+
controller = new AbortController();
|
| 301 |
+
let pending = false;
|
| 302 |
+
const render = () => { if (pending) return; pending = true; requestAnimationFrame(() => { pending = false; if (a.seg) a.seg.innerHTML = md(a.raw); scroll(); }); };
|
| 303 |
+
try {
|
| 304 |
+
const r = await api('/api/chat', { method: 'POST', body: JSON.stringify({ message: text, conversation_id: currentId, model: $('#modelSel').value || null, project_id: isRealProject() ? curProject : null }), signal: controller.signal });
|
| 305 |
+
const reader = r.body.getReader(), dec = new TextDecoder(); let buf = '';
|
| 306 |
+
while (true) {
|
| 307 |
+
const { value, done } = await reader.read(); if (done) break;
|
| 308 |
+
buf += dec.decode(value, { stream: true });
|
| 309 |
+
let i;
|
| 310 |
+
while ((i = buf.indexOf('\n\n')) >= 0) {
|
| 311 |
+
const line = buf.slice(0, i).trim(); buf = buf.slice(i + 2);
|
| 312 |
+
if (!line.startsWith('data:')) continue;
|
| 313 |
+
const ev = JSON.parse(line.slice(5));
|
| 314 |
+
if (ev.type === 'conversation') {
|
| 315 |
+
if (currentId !== ev.id) { currentId = ev.id; $('#title').textContent = text.slice(0, 40); loadConvs(); }
|
| 316 |
+
} else if (ev.type === 'reasoning') {
|
| 317 |
+
if (!a.think) { a.think = document.createElement('details'); a.think.className = 'think'; a.think.innerHTML = '<summary>💭 思考過程</summary><pre></pre>'; a.el.insertBefore(a.think, a.el.firstChild); }
|
| 318 |
+
a.think.querySelector('pre').textContent += ev.text;
|
| 319 |
+
} else if (ev.type === 'token') { textSeg(a); a.raw += ev.text; render(); }
|
| 320 |
+
else if (ev.type === 'tool_start') { toolBlock(a, ev.id, ev.name, ev.arguments); scroll(); }
|
| 321 |
+
else if (ev.type === 'tool_result') { toolResult(a, ev.id, ev.result); a.think = a.think; scroll(); }
|
| 322 |
+
else if (ev.type === 'error') { const e = document.createElement('div'); e.className = 'err'; e.textContent = '⚠️ ' + ev.message; a.el.appendChild(e); }
|
| 323 |
+
}
|
| 324 |
+
}
|
| 325 |
+
} catch (err) {
|
| 326 |
+
if (err.name !== 'AbortError') { const e = document.createElement('div'); e.className = 'err'; e.textContent = '⚠️ ' + err.message; a.el.appendChild(e); }
|
| 327 |
+
} finally {
|
| 328 |
+
if (a.seg) a.seg.innerHTML = md(a.raw);
|
| 329 |
+
a.el.classList.remove('cursor'); busy = false; controller = null;
|
| 330 |
+
$('#sendBtn').textContent = '送出'; $('#sendBtn').classList.add('primary'); loadConvs().catch(() => {});
|
| 331 |
+
}
|
| 332 |
+
}
|
| 333 |
+
$('#sendBtn').onclick = () => busy ? controller?.abort() : send();
|
| 334 |
+
const autosize = () => { const t = $('#input'); t.style.height = 'auto'; t.style.height = Math.min(t.scrollHeight, 220) + 'px'; };
|
| 335 |
+
$('#input').addEventListener('input', autosize);
|
| 336 |
+
$('#input').addEventListener('keydown', e => { if (e.key === 'Enter' && !e.shiftKey && !e.isComposing) { e.preventDefault(); send(); } });
|
| 337 |
+
|
| 338 |
+
// ---------- 設定 ----------
|
| 339 |
+
$('#setBtn').onclick = async () => {
|
| 340 |
+
const s = await (await api('/api/settings')).json();
|
| 341 |
+
$('#setPrompt').value = s.system_prompt || s.default_system_prompt; $('#setModal').classList.remove('hidden');
|
| 342 |
+
};
|
| 343 |
+
$('#setCancel').onclick = () => $('#setModal').classList.add('hidden');
|
| 344 |
+
$('#setSave').onclick = async () => {
|
| 345 |
+
await api('/api/settings', { method: 'PUT', body: JSON.stringify({ system_prompt: $('#setPrompt').value }) });
|
| 346 |
+
$('#setModal').classList.add('hidden');
|
| 347 |
+
};
|
| 348 |
+
|
| 349 |
+
// ---------- 記憶 ----------
|
| 350 |
+
async function loadMems() {
|
| 351 |
+
const list = await (await api('/api/memories')).json(); const box = $('#memList'); box.innerHTML = '';
|
| 352 |
+
if (!list.length) box.innerHTML = '<div style="color:var(--muted)">還沒有記憶。</div>';
|
| 353 |
+
for (const m of list) {
|
| 354 |
+
const d = document.createElement('div'); d.className = 'mem';
|
| 355 |
+
d.innerHTML = `<div class="c">${esc(m.content)}<div class="id">#${m.id} ${esc(m.tags || '')} · ${new Date(m.created_at).toLocaleString()}</div></div><button>刪除</button>`;
|
| 356 |
+
d.querySelector('button').onclick = async () => { await api('/api/memories/' + m.id, { method: 'DELETE' }); loadMems(); };
|
| 357 |
+
box.appendChild(d);
|
| 358 |
+
}
|
| 359 |
+
}
|
| 360 |
+
$('#memBtn').onclick = async () => { await loadMems(); $('#memModal').classList.remove('hidden'); };
|
| 361 |
+
$('#memClose').onclick = () => $('#memModal').classList.add('hidden');
|
| 362 |
+
$('#memAdd').onclick = async () => {
|
| 363 |
+
const v = $('#memNew').value.trim(); if (!v) return;
|
| 364 |
+
await api('/api/memories', { method: 'POST', body: JSON.stringify({ content: v }) }); $('#memNew').value = ''; loadMems();
|
| 365 |
+
};
|
| 366 |
+
|
| 367 |
+
// ---------- 專案 ----------
|
| 368 |
+
let curProject = localStorage.getItem('agent_project') || 'all', projMap = {}, editingProj = null, projFiles = [];
|
| 369 |
+
const isRealProject = () => curProject && curProject !== 'all' && curProject !== 'none' && projMap[curProject];
|
| 370 |
+
async function loadProjects() {
|
| 371 |
+
const list = await (await api('/api/projects')).json(); projMap = {};
|
| 372 |
+
const sel = $('#projSel'); sel.innerHTML = '';
|
| 373 |
+
sel.appendChild(new Option('全部對話', 'all')); sel.appendChild(new Option('未歸類對話', 'none'));
|
| 374 |
+
for (const p of list) { projMap[p.id] = p; sel.appendChild(new Option('📁 ' + p.name, p.id)); }
|
| 375 |
+
sel.appendChild(new Option('+ 新增專案…', '__new'));
|
| 376 |
+
if (curProject !== 'all' && curProject !== 'none' && !projMap[curProject]) curProject = 'all';
|
| 377 |
+
sel.value = curProject;
|
| 378 |
+
}
|
| 379 |
+
$('#projSel').onchange = async e => {
|
| 380 |
+
if (e.target.value === '__new') { e.target.value = curProject; return openProject(null); }
|
| 381 |
+
curProject = e.target.value; localStorage.setItem('agent_project', curProject);
|
| 382 |
+
await loadConvs(); newChat();
|
| 383 |
+
};
|
| 384 |
+
$('#projBtn').onclick = () => openProject(isRealProject() ? curProject : null);
|
| 385 |
+
async function openProject(pid) {
|
| 386 |
+
editingProj = pid; $('#projMsg').textContent = ''; $('#projFlt').value = '';
|
| 387 |
+
const p = pid ? projMap[pid] : null;
|
| 388 |
+
$('#projTitle').textContent = p ? '專案:' + p.name : '新增專案';
|
| 389 |
+
$('#projName').value = p ? p.name : ''; $('#projInstr').value = p ? (p.instructions || '') : '';
|
| 390 |
+
$('#projFilesBox').style.display = p ? 'block' : 'none'; $('#projDel').style.display = p ? '' : 'none';
|
| 391 |
+
$('#projModal').classList.remove('hidden');
|
| 392 |
+
if (p) await loadProjFiles();
|
| 393 |
+
}
|
| 394 |
+
async function loadProjFiles() {
|
| 395 |
+
projFiles = await (await api(`/api/projects/${editingProj}/files`)).json(); renderProjFiles();
|
| 396 |
+
}
|
| 397 |
+
function fmtSize(n) { return n < 1024 ? n + ' B' : n < 1048576 ? (n / 1024).toFixed(1) + ' KB' : (n / 1048576).toFixed(1) + ' MB'; }
|
| 398 |
+
function renderProjFiles() {
|
| 399 |
+
const box = $('#projFiles'); box.innerHTML = ''; const f = $('#projFlt').value.trim().toLowerCase();
|
| 400 |
+
const list = projFiles.filter(x => !f || x.path.toLowerCase().includes(f));
|
| 401 |
+
if (!list.length) { box.innerHTML = `<div class="id">${projFiles.length ? '沒有符合的檔案' : '還沒有檔案(agent 寫的、你上傳的都會出現在這裡)'}</div>`; return; }
|
| 402 |
+
for (const x of list) {
|
| 403 |
+
const r = document.createElement('div'); r.style.cssText = 'display:flex;gap:6px;align-items:center;padding:2px 0';
|
| 404 |
+
r.innerHTML = `<span style="flex:1;word-break:break-all">${esc(x.path)}</span><span class="id">${fmtSize(x.size || 0)}</span><button class="dl">下載</button><button class="rm">刪除</button>`;
|
| 405 |
+
r.querySelector('.dl').onclick = () => downloadBlob(`/api/projects/${editingProj}/file?path=${encodeURIComponent(x.path)}`, x.path.split('/').pop());
|
| 406 |
+
r.querySelector('.rm').onclick = async () => { if (!confirm('刪除 ' + x.path + '?')) return; await api(`/api/projects/${editingProj}/file?path=${encodeURIComponent(x.path)}`, { method: 'DELETE' }); loadProjFiles(); };
|
| 407 |
+
box.appendChild(r);
|
| 408 |
+
}
|
| 409 |
+
}
|
| 410 |
+
$('#projFlt').oninput = renderProjFiles;
|
| 411 |
+
async function downloadBlob(url, name) {
|
| 412 |
+
const r = await api(url); const b = await r.blob(); const a = document.createElement('a');
|
| 413 |
+
a.href = URL.createObjectURL(b); a.download = name; a.click(); setTimeout(() => URL.revokeObjectURL(a.href), 5000);
|
| 414 |
+
}
|
| 415 |
+
const toB64 = f => new Promise((ok, no) => { const r = new FileReader(); r.onload = () => ok(r.result.split(',')[1] || ''); r.onerror = no; r.readAsDataURL(f); });
|
| 416 |
+
async function uploadFiles(files) {
|
| 417 |
+
const skip = /(^|\/)(node_modules|\.git|\.venv|venv|__pycache__|dist|build|\.next)(\/|$)/;
|
| 418 |
+
const list = [...files].filter(f => !skip.test(f.webkitRelativePath || f.name)); let n = 0;
|
| 419 |
+
for (const f of list) {
|
| 420 |
+
$('#projMsg').textContent = `上傳中 ${++n}/${list.length}:${f.webkitRelativePath || f.name}`;
|
| 421 |
+
try { await api(`/api/projects/${editingProj}/files`, { method: 'POST', body: JSON.stringify({ path: f.webkitRelativePath || f.name, b64: await toB64(f) }) }); }
|
| 422 |
+
catch (e) { $('#projMsg').textContent = '⚠️ ' + (f.webkitRelativePath || f.name) + ':' + e.message; return; }
|
| 423 |
+
}
|
| 424 |
+
$('#projMsg').textContent = `✓ 已上傳 ${list.length} 個檔案`; loadProjFiles();
|
| 425 |
+
}
|
| 426 |
+
$('#projUpFiles').onclick = () => $('#projFileIn').click();
|
| 427 |
+
$('#projUpDir').onclick = () => $('#projDirIn').click();
|
| 428 |
+
$('#projFileIn').onchange = e => { uploadFiles(e.target.files); e.target.value = ''; };
|
| 429 |
+
$('#projDirIn').onchange = e => { uploadFiles(e.target.files); e.target.value = ''; };
|
| 430 |
+
$('#projZip').onclick = () => downloadBlob(`/api/projects/${editingProj}/zip`, (projMap[editingProj]?.name || 'project') + '.zip');
|
| 431 |
+
$('#projClose').onclick = () => $('#projModal').classList.add('hidden');
|
| 432 |
+
$('#projSave').onclick = async () => {
|
| 433 |
+
const body = JSON.stringify({ name: $('#projName').value.trim() || '未命名專案', instructions: $('#projInstr').value });
|
| 434 |
+
try {
|
| 435 |
+
const p = await (await api(editingProj ? `/api/projects/${editingProj}` : '/api/projects', { method: editingProj ? 'PATCH' : 'POST', body })).json();
|
| 436 |
+
const isNew = !editingProj; await loadProjects();
|
| 437 |
+
if (isNew) { curProject = p.id; localStorage.setItem('agent_project', p.id); $('#projSel').value = p.id; await loadConvs(); newChat(); openProject(p.id); }
|
| 438 |
+
else $('#projModal').classList.add('hidden');
|
| 439 |
+
} catch (e) { $('#projMsg').textContent = '⚠️ ' + e.message; }
|
| 440 |
+
};
|
| 441 |
+
$('#projDel').onclick = async () => {
|
| 442 |
+
if (!confirm('刪除專案和它的所有檔案?(對話會保留,變成未歸類)')) return;
|
| 443 |
+
await api(`/api/projects/${editingProj}`, { method: 'DELETE' }); $('#projModal').classList.add('hidden');
|
| 444 |
+
curProject = 'all'; localStorage.setItem('agent_project', 'all'); await loadProjects(); await loadConvs(); newChat();
|
| 445 |
+
};
|
| 446 |
+
|
| 447 |
+
// ---------- 模型提供商 ----------
|
| 448 |
+
let provState = { providers: [], selected: '' };
|
| 449 |
+
const SEP = '::';
|
| 450 |
+
async function loadModelSel() {
|
| 451 |
+
provState = await (await api('/api/providers')).json();
|
| 452 |
+
const sel = $('#modelSel'); sel.innerHTML = '';
|
| 453 |
+
for (const p of provState.providers.filter(p => p.enabled !== false))
|
| 454 |
+
for (const m of p.models) { const o = new Option(`${p.name} · ${m}`, p.id + SEP + m); sel.appendChild(o); }
|
| 455 |
+
sel.insertBefore(new Option(sel.options.length ? '選擇模型…' : '⚠️ 先到「🤖 模型」新增提供商', ''), sel.firstChild);
|
| 456 |
+
sel.value = (provState.selected && [...sel.options].some(o => o.value === provState.selected)) ? provState.selected : '';
|
| 457 |
+
}
|
| 458 |
+
// 隨時切換:對話中切換只影響這個對話(下一則訊息起生效);新對話時切換=改預設
|
| 459 |
+
$('#modelSel').onchange = async e => {
|
| 460 |
+
if (!e.target.value) return $('#provBtn').click();
|
| 461 |
+
if (currentId) await api('/api/conversations/' + currentId, { method: 'PATCH', body: JSON.stringify({ model: e.target.value }) });
|
| 462 |
+
else { provState.selected = e.target.value; await api('/api/providers', { method: 'PUT', body: JSON.stringify({ providers: provState.providers, selected: e.target.value }) }); }
|
| 463 |
+
};
|
| 464 |
+
function setModelSel(v) { const sel = $('#modelSel'); const t = v || provState.selected; sel.value = (t && [...sel.options].some(o => o.value === t)) ? t : ''; }
|
| 465 |
+
function provCard(p, i, all) {
|
| 466 |
+
const d = document.createElement('div'); d.className = 'mem'; d.style.flexDirection = 'column';
|
| 467 |
+
p.available = p.available || []; p.models = p.models || [];
|
| 468 |
+
d.innerHTML = `
|
| 469 |
+
<div style="display:flex;gap:6px;width:100%;align-items:center">
|
| 470 |
+
<input type="checkbox" class="en" style="width:auto" title="啟用" ${p.enabled !== false ? 'checked' : ''}>
|
| 471 |
+
<input class="nm" placeholder="名稱" style="flex:1">
|
| 472 |
+
<button class="rm">刪除</button>
|
| 473 |
+
</div>
|
| 474 |
+
<input class="bu" placeholder="Base URL(OpenAI 相容,例如 https://xxx/v1)">
|
| 475 |
+
<div style="display:flex;gap:6px;width:100%"><input class="ky" type="password" placeholder="API key 或 \${VAR}" style="flex:1"><button class="pull">拉取模型</button></div>
|
| 476 |
+
<div class="pick" style="width:100%;display:${p.available.length ? 'block' : 'none'}">
|
| 477 |
+
<div style="display:flex;gap:6px"><input class="flt" placeholder="篩選模型,例如 :free、flash、coder" style="flex:1"><button class="all">全選結果</button><button class="none">清空</button></div>
|
| 478 |
+
<div class="lst" style="max-height:220px;overflow:auto;border:1px solid var(--line);border-radius:6px;padding:6px;margin-top:6px;font-size:13px"></div>
|
| 479 |
+
</div>
|
| 480 |
+
<div style="display:flex;gap:6px;width:100%"><input class="add" placeholder="手動加模型 ID,Enter 加入" style="flex:1"></div>
|
| 481 |
+
<div class="chips" style="display:flex;gap:6px;flex-wrap:wrap;width:100%"></div>
|
| 482 |
+
<div class="hint id"></div>`;
|
| 483 |
+
const q = c => d.querySelector(c);
|
| 484 |
+
q('.nm').value = p.name || ''; q('.bu').value = p.base_url || ''; q('.ky').value = p.api_key || '';
|
| 485 |
+
q('.en').onchange = e => p.enabled = e.target.checked;
|
| 486 |
+
q('.nm').oninput = e => p.name = e.target.value;
|
| 487 |
+
q('.bu').oninput = e => p.base_url = e.target.value;
|
| 488 |
+
q('.ky').oninput = e => p.api_key = e.target.value;
|
| 489 |
+
const chips = () => {
|
| 490 |
+
q('.chips').innerHTML = p.models.length ? '' : '<span class="id">還沒選模型</span>';
|
| 491 |
+
p.models.forEach((m, k) => {
|
| 492 |
+
const c = document.createElement('span'); c.className = 'chip';
|
| 493 |
+
c.style.cssText = 'border:1px solid var(--line);border-radius:12px;padding:2px 8px;font-size:12px;cursor:pointer';
|
| 494 |
+
c.title = '點擊移除'; c.textContent = m + ' ✕'; c.onclick = () => { p.models.splice(k, 1); chips(); list(); };
|
| 495 |
+
q('.chips').appendChild(c);
|
| 496 |
+
});
|
| 497 |
+
};
|
| 498 |
+
const matches = () => { const f = q('.flt').value.trim().toLowerCase(); return p.available.filter(m => !f || f.split(/\s+/).every(w => m.toLowerCase().includes(w))); };
|
| 499 |
+
const list = () => {
|
| 500 |
+
const box = q('.lst'); box.innerHTML = ''; const ms = matches();
|
| 501 |
+
q('.pick').style.display = p.available.length ? 'block' : 'none';
|
| 502 |
+
for (const m of ms.slice(0, 500)) {
|
| 503 |
+
const l = document.createElement('label'); l.style.cssText = 'display:flex;gap:6px;align-items:center;margin:0;color:inherit';
|
| 504 |
+
l.innerHTML = `<input type="checkbox" style="width:auto" ${p.models.includes(m) ? 'checked' : ''}><span>${esc(m)}</span>`;
|
| 505 |
+
l.querySelector('input').onchange = e => { if (e.target.checked) { if (!p.models.includes(m)) p.models.push(m); } else p.models = p.models.filter(x => x !== m); chips(); };
|
| 506 |
+
box.appendChild(l);
|
| 507 |
+
}
|
| 508 |
+
if (ms.length > 500) box.insertAdjacentHTML('beforeend', `<div class="id">還有 ${ms.length - 500} 個,請再篩選</div>`);
|
| 509 |
+
if (!ms.length) box.innerHTML = '<div class="id">沒有符合的模型</div>';
|
| 510 |
+
};
|
| 511 |
+
q('.flt').oninput = list;
|
| 512 |
+
q('.all').onclick = () => { for (const m of matches()) if (!p.models.includes(m)) p.models.push(m); chips(); list(); };
|
| 513 |
+
q('.none').onclick = () => { p.models = []; chips(); list(); };
|
| 514 |
+
q('.add').onkeydown = e => { if (e.key !== 'Enter') return; const v = e.target.value.trim(); if (v && !p.models.includes(v)) p.models.push(v); e.target.value = ''; chips(); list(); };
|
| 515 |
+
q('.pull').onclick = async () => {
|
| 516 |
+
q('.pull').textContent = '拉取中…';
|
| 517 |
+
try {
|
| 518 |
+
const r = await (await api('/api/providers/models', { method: 'POST', body: JSON.stringify({ base_url: p.base_url, api_key: p.api_key || '', id: p.id || null }) })).json();
|
| 519 |
+
p.available = r.models; q('.hint').textContent = `共 ${r.models.length} 個模型`; list();
|
| 520 |
+
} catch (e) { q('.hint').textContent = '⚠️ ' + e.message; }
|
| 521 |
+
q('.pull').textContent = '拉取模型';
|
| 522 |
+
};
|
| 523 |
+
q('.rm').onclick = () => { if (confirm('刪除 ' + (p.name || '這個提供商') + '?')) { all.splice(i, 1); renderProv(); } };
|
| 524 |
+
chips(); list();
|
| 525 |
+
return d;
|
| 526 |
+
}
|
| 527 |
+
function renderProv() {
|
| 528 |
+
const box = $('#provList'); box.innerHTML = '';
|
| 529 |
+
if (!provState.providers.length) box.innerHTML = '<div style="color:var(--muted)">還沒有提供商。</div>';
|
| 530 |
+
provState.providers.forEach((p, i, all) => box.appendChild(provCard(p, i, all)));
|
| 531 |
+
}
|
| 532 |
+
$('#provBtn').onclick = async () => {
|
| 533 |
+
provState = await (await api('/api/providers')).json();
|
| 534 |
+
$('#provMsg').textContent = ''; renderProv();
|
| 535 |
+
$('#provModal').classList.remove('hidden');
|
| 536 |
+
};
|
| 537 |
+
$('#provAdd').onclick = () => { provState.providers.push({ name: '', base_url: '', api_key: '', models: [], available: [], enabled: true }); renderProv(); };
|
| 538 |
+
$('#provClose').onclick = () => $('#provModal').classList.add('hidden');
|
| 539 |
+
$('#provSave').onclick = async () => {
|
| 540 |
+
try {
|
| 541 |
+
const body = { providers: provState.providers, selected: provState.selected || null };
|
| 542 |
+
provState = await (await api('/api/providers', { method: 'PUT', body: JSON.stringify(body) })).json();
|
| 543 |
+
$('#provModal').classList.add('hidden'); loadModelSel();
|
| 544 |
+
} catch (e) { $('#provMsg').textContent = '⚠️ ' + e.message; }
|
| 545 |
+
};
|
| 546 |
+
|
| 547 |
+
// ---------- 技能 ----------
|
| 548 |
+
async function loadSkills() {
|
| 549 |
+
const list = await (await api('/api/skills')).json(); const box = $('#skillList'); box.innerHTML = '';
|
| 550 |
+
if (!list.length) box.innerHTML = '<div style="color:var(--muted)">還沒有安裝技能。</div>';
|
| 551 |
+
for (const k of list) {
|
| 552 |
+
const d = document.createElement('div'); d.className = 'mem';
|
| 553 |
+
d.innerHTML = `<input type="checkbox" style="width:auto;margin-top:4px" ${k.enabled ? 'checked' : ''} title="啟用">
|
| 554 |
+
<div class="c"><b>${esc(k.name)}</b> — ${esc(k.description)}<div class="id">${esc(k.source || '')}</div></div><button>刪除</button>`;
|
| 555 |
+
d.querySelector('input').onchange = async e => api('/api/skills/' + encodeURIComponent(k.name), { method: 'PATCH', body: JSON.stringify({ enabled: e.target.checked }) });
|
| 556 |
+
d.querySelector('button').onclick = async () => { if (!confirm('刪除技能 ' + k.name + '?')) return; await api('/api/skills/' + encodeURIComponent(k.name), { method: 'DELETE' }); loadSkills(); };
|
| 557 |
+
box.appendChild(d);
|
| 558 |
+
}
|
| 559 |
+
}
|
| 560 |
+
async function installSkill(payload) {
|
| 561 |
+
$('#skillMsg').textContent = '安裝中…';
|
| 562 |
+
try {
|
| 563 |
+
const r = await (await api('/api/skills/install', { method: 'POST', body: JSON.stringify(payload) })).json();
|
| 564 |
+
$('#skillMsg').textContent = `✓ 已安裝 ${r.name}(${r.files.length} 個檔案)`; $('#skillUrl').value = ''; $('#skillPaste').value = ''; loadSkills();
|
| 565 |
+
} catch (e) { $('#skillMsg').textContent = '⚠️ ' + e.message; }
|
| 566 |
+
}
|
| 567 |
+
$('#skillBtn').onclick = async () => { $('#skillMsg').textContent = ''; await loadSkills(); $('#skillModal').classList.remove('hidden'); };
|
| 568 |
+
$('#skillClose').onclick = () => $('#skillModal').classList.add('hidden');
|
| 569 |
+
$('#skillInstall').onclick = () => { const v = $('#skillUrl').value.trim(); if (v) installSkill({ source: v }); };
|
| 570 |
+
$('#skillPasteInstall').onclick = () => { const v = $('#skillPaste').value.trim(); if (v) installSkill({ content: v }); };
|
| 571 |
+
|
| 572 |
+
// ---------- MCP ----------
|
| 573 |
+
function renderMcpStatus(st) {
|
| 574 |
+
const box = $('#mcpStatus'); box.innerHTML = '';
|
| 575 |
+
if (!st.length) { box.innerHTML = '<div style="color:var(--muted)">沒有設定 MCP 伺服器。</div>'; return; }
|
| 576 |
+
for (const s of st) {
|
| 577 |
+
const d = document.createElement('div'); d.className = 'mem';
|
| 578 |
+
d.innerHTML = `<div class="c">${s.connected ? '🟢' : '🔴'} <b>${esc(s.name)}</b> ${s.connected ? `· ${s.tools.length} 個工具` : ''}
|
| 579 |
+
<div class="id">${s.connected ? esc(s.tools.join(', ')) : esc(s.error || '未連線')}</div></div>`;
|
| 580 |
+
box.appendChild(d);
|
| 581 |
+
}
|
| 582 |
+
}
|
| 583 |
+
$('#mcpBtn').onclick = async () => {
|
| 584 |
+
const r = await (await api('/api/mcp')).json(); $('#mcpConfig').value = r.config; renderMcpStatus(r.status);
|
| 585 |
+
$('#mcpModal').classList.remove('hidden');
|
| 586 |
+
};
|
| 587 |
+
$('#mcpClose').onclick = () => $('#mcpModal').classList.add('hidden');
|
| 588 |
+
$('#mcpSave').onclick = async () => {
|
| 589 |
+
$('#mcpStatus').textContent = '連線中…';
|
| 590 |
+
try { const r = await (await api('/api/mcp', { method: 'PUT', body: JSON.stringify({ config: $('#mcpConfig').value }) })).json(); renderMcpStatus(r.status); }
|
| 591 |
+
catch (e) { $('#mcpStatus').textContent = '⚠️ ' + e.message; }
|
| 592 |
+
};
|
| 593 |
+
$('#mcpReload').onclick = async () => {
|
| 594 |
+
$('#mcpStatus').textContent = '連線中…';
|
| 595 |
+
const r = await (await api('/api/mcp/reload', { method: 'POST' })).json(); renderMcpStatus(r.status);
|
| 596 |
+
};
|
| 597 |
+
|
| 598 |
+
boot();
|
| 599 |
+
</script>
|
| 600 |
+
</body>
|
| 601 |
+
</html>
|
app/tools.py
ADDED
|
@@ -0,0 +1,342 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Agent 可用的工具。新增工具:寫一個 async 函數,再在 TOOLS 裡登記 schema 即可。"""
|
| 2 |
+
import asyncio
|
| 3 |
+
import ipaddress
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
import resource
|
| 7 |
+
import socket
|
| 8 |
+
import sys
|
| 9 |
+
import tempfile
|
| 10 |
+
from datetime import datetime
|
| 11 |
+
from urllib.parse import urlparse
|
| 12 |
+
from zoneinfo import ZoneInfo
|
| 13 |
+
|
| 14 |
+
import httpx
|
| 15 |
+
from bs4 import BeautifulSoup
|
| 16 |
+
|
| 17 |
+
from . import config
|
| 18 |
+
from . import db as store
|
| 19 |
+
from . import skills as skillmod
|
| 20 |
+
from . import workspace
|
| 21 |
+
from .mcp_client import manager as mcp
|
| 22 |
+
|
| 23 |
+
UA = ("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
|
| 24 |
+
"(KHTML, like Gecko) Chrome/126.0 Safari/537.36")
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
# ---------- 網路搜尋 ----------
|
| 28 |
+
async def web_search(query: str, max_results: int = 5):
|
| 29 |
+
max_results = max(1, min(int(max_results), 10))
|
| 30 |
+
async with httpx.AsyncClient(timeout=20, headers={"User-Agent": UA}, follow_redirects=True) as c:
|
| 31 |
+
if config.TAVILY_API_KEY:
|
| 32 |
+
r = await c.post(
|
| 33 |
+
"https://api.tavily.com/search",
|
| 34 |
+
headers={"Authorization": f"Bearer {config.TAVILY_API_KEY}"},
|
| 35 |
+
json={"api_key": config.TAVILY_API_KEY, "query": query, "max_results": max_results},
|
| 36 |
+
)
|
| 37 |
+
r.raise_for_status()
|
| 38 |
+
return [{"title": x.get("title"), "url": x.get("url"), "snippet": x.get("content")}
|
| 39 |
+
for x in r.json().get("results", [])]
|
| 40 |
+
# 沒有 Tavily:用 ddgs(多後端元搜尋,HF 等機房 IP 也能用)
|
| 41 |
+
def _ddgs():
|
| 42 |
+
from ddgs import DDGS
|
| 43 |
+
return DDGS().text(query, max_results=max_results) or []
|
| 44 |
+
rows = await asyncio.to_thread(_ddgs)
|
| 45 |
+
out = [{"title": x.get("title"), "url": x.get("href"), "snippet": x.get("body")} for x in rows]
|
| 46 |
+
return out or {"error": "沒有搜尋結果(可設定 TAVILY_API_KEY 換更穩的搜尋)"}
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
# ---------- 讀網頁 ----------
|
| 50 |
+
def _is_public_host(host: str) -> bool:
|
| 51 |
+
try:
|
| 52 |
+
infos = socket.getaddrinfo(host, None)
|
| 53 |
+
except socket.gaierror:
|
| 54 |
+
return False
|
| 55 |
+
for info in infos:
|
| 56 |
+
ip = ipaddress.ip_address(info[4][0])
|
| 57 |
+
if ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_reserved or ip.is_multicast:
|
| 58 |
+
return False
|
| 59 |
+
return True
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
async def fetch_url(url: str, max_chars: int = 8000):
|
| 63 |
+
p = urlparse(url)
|
| 64 |
+
if p.scheme not in ("http", "https") or not p.hostname:
|
| 65 |
+
return {"error": "只支援 http/https 網址"}
|
| 66 |
+
if not await asyncio.to_thread(_is_public_host, p.hostname):
|
| 67 |
+
return {"error": "拒絕訪問內網或無法解析的位址"}
|
| 68 |
+
async with httpx.AsyncClient(timeout=25, headers={"User-Agent": UA}, follow_redirects=True) as c:
|
| 69 |
+
r = await c.get(url)
|
| 70 |
+
ct = r.headers.get("content-type", "").lower()
|
| 71 |
+
if ct and not any(k in ct for k in ("text", "html", "json", "xml")):
|
| 72 |
+
return {"url": str(r.url), "status": r.status_code, "error": f"不支援的內容類型: {ct}"}
|
| 73 |
+
title = ""
|
| 74 |
+
if "html" in ct or r.text.lstrip()[:15].lower().startswith(("<!doctype", "<html")):
|
| 75 |
+
soup = BeautifulSoup(r.text, "html.parser")
|
| 76 |
+
for t in soup(["script", "style", "noscript", "nav", "footer", "header", "aside", "form", "svg", "iframe"]):
|
| 77 |
+
t.decompose()
|
| 78 |
+
title = soup.title.get_text(strip=True) if soup.title else ""
|
| 79 |
+
text = soup.get_text("\n", strip=True)
|
| 80 |
+
else:
|
| 81 |
+
text = r.text
|
| 82 |
+
text = "\n".join(line for line in text.splitlines() if line.strip())
|
| 83 |
+
max_chars = max(500, min(int(max_chars), 30000))
|
| 84 |
+
return {"url": str(r.url), "status": r.status_code, "title": title,
|
| 85 |
+
"content": text[:max_chars], "truncated": len(text) > max_chars}
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
# ---------- 執行 Python ----------
|
| 89 |
+
def _limits(mem_gb: int = 2):
|
| 90 |
+
def apply():
|
| 91 |
+
mem = mem_gb * 1024 ** 3
|
| 92 |
+
resource.setrlimit(resource.RLIMIT_AS, (mem, mem))
|
| 93 |
+
resource.setrlimit(resource.RLIMIT_CPU, (300, 300))
|
| 94 |
+
return apply
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def _sandbox_env() -> dict:
|
| 98 |
+
# 乾淨的環境變數:子程序看不到 API key / 資料庫 token
|
| 99 |
+
home = os.path.join(config.WORKDIR, ".home")
|
| 100 |
+
os.makedirs(home, exist_ok=True)
|
| 101 |
+
return {"PATH": f"{home}/.local/bin:" + os.environ.get("PATH", ""), "HOME": home, "MPLBACKEND": "Agg",
|
| 102 |
+
"PYTHONIOENCODING": "utf-8", "LANG": "C.UTF-8", "SKILLS_DIR": config.SKILLS_DIR}
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
async def _run(argv: list[str], timeout: int, mem_gb: int) -> dict:
|
| 106 |
+
proc = await asyncio.create_subprocess_exec(
|
| 107 |
+
*argv, cwd=str(workspace.current_dir()), env=_sandbox_env(),
|
| 108 |
+
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, preexec_fn=_limits(mem_gb),
|
| 109 |
+
)
|
| 110 |
+
try:
|
| 111 |
+
out, err = await asyncio.wait_for(proc.communicate(), timeout)
|
| 112 |
+
except asyncio.TimeoutError:
|
| 113 |
+
proc.kill()
|
| 114 |
+
await proc.wait()
|
| 115 |
+
await workspace.sync()
|
| 116 |
+
return {"error": f"執行逾時({timeout} 秒)"}
|
| 117 |
+
synced = await workspace.sync()
|
| 118 |
+
res = {"exit_code": proc.returncode,
|
| 119 |
+
"stdout": out.decode(errors="replace")[-10000:],
|
| 120 |
+
"stderr": err.decode(errors="replace")[-5000:]}
|
| 121 |
+
if synced["changed"] or synced["deleted"]:
|
| 122 |
+
res["files_saved"] = synced["changed"][:50]
|
| 123 |
+
res["files_deleted"] = synced["deleted"][:50]
|
| 124 |
+
return res
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
async def run_python(code: str, timeout: int = 30):
|
| 128 |
+
if not config.ENABLE_PYTHON_TOOL:
|
| 129 |
+
return {"error": "Python 工具已停用"}
|
| 130 |
+
timeout = max(1, min(int(timeout), 300))
|
| 131 |
+
with tempfile.NamedTemporaryFile("w", suffix=".py", delete=False, encoding="utf-8") as f:
|
| 132 |
+
f.write(code)
|
| 133 |
+
path = f.name
|
| 134 |
+
try:
|
| 135 |
+
return await _run([sys.executable, "-I", path], timeout, 2)
|
| 136 |
+
finally:
|
| 137 |
+
os.unlink(path)
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
async def run_shell(command: str, timeout: int = 60):
|
| 141 |
+
if not config.ENABLE_SHELL_TOOL:
|
| 142 |
+
return {"error": "Shell 工具已停用"}
|
| 143 |
+
timeout = max(1, min(int(timeout), 600))
|
| 144 |
+
return await _run(["bash", "-c", command], timeout, 8)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
# ---------- 專案檔案 ----------
|
| 148 |
+
async def list_files(path: str = ".", max_entries: int = 300):
|
| 149 |
+
root = workspace.current_dir()
|
| 150 |
+
base = workspace.safe_path(path)
|
| 151 |
+
if not base.exists():
|
| 152 |
+
return {"error": f"不存在:{path}"}
|
| 153 |
+
out = []
|
| 154 |
+
for rel in workspace.tree(workspace.current_project.get(), limit=100000):
|
| 155 |
+
full = root / rel
|
| 156 |
+
if base == root or base in full.parents:
|
| 157 |
+
out.append(f"{rel} ({full.stat().st_size} B)")
|
| 158 |
+
if len(out) >= max_entries:
|
| 159 |
+
out.append("…(已截斷,請指定子目錄)")
|
| 160 |
+
break
|
| 161 |
+
return {"root": str(root), "files": out}
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
async def read_file(path: str, start_line: int = 1, max_lines: int = 400):
|
| 165 |
+
fp = workspace.safe_path(path)
|
| 166 |
+
if not fp.is_file():
|
| 167 |
+
return {"error": f"不是檔案:{path}"}
|
| 168 |
+
try:
|
| 169 |
+
lines = fp.read_text(encoding="utf-8").splitlines()
|
| 170 |
+
except UnicodeDecodeError:
|
| 171 |
+
return {"error": "二進位檔,無法以文字讀取", "size": fp.stat().st_size}
|
| 172 |
+
start = max(1, int(start_line))
|
| 173 |
+
chunk = lines[start - 1:start - 1 + max(1, min(int(max_lines), 2000))]
|
| 174 |
+
return {"path": path, "total_lines": len(lines), "start_line": start,
|
| 175 |
+
"content": "\n".join(f"{start + i:>5}| {ln}" for i, ln in enumerate(chunk))}
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
async def write_file(path: str, content: str):
|
| 179 |
+
fp = workspace.safe_path(path)
|
| 180 |
+
fp.parent.mkdir(parents=True, exist_ok=True)
|
| 181 |
+
fp.write_text(content, encoding="utf-8")
|
| 182 |
+
await workspace.sync()
|
| 183 |
+
return {"ok": True, "path": path, "bytes": len(content.encode())}
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
async def edit_file(path: str, old_string: str, new_string: str, replace_all: bool = False):
|
| 187 |
+
fp = workspace.safe_path(path)
|
| 188 |
+
if not fp.is_file():
|
| 189 |
+
return {"error": f"不是檔案:{path}"}
|
| 190 |
+
text = fp.read_text(encoding="utf-8")
|
| 191 |
+
n = text.count(old_string)
|
| 192 |
+
if n == 0:
|
| 193 |
+
return {"error": "找不到 old_string(要和檔案內容完全一致,包括縮排)"}
|
| 194 |
+
if n > 1 and not replace_all:
|
| 195 |
+
return {"error": f"old_string 出現 {n} 次,請多帶幾行上下文讓它唯一,或設 replace_all=true"}
|
| 196 |
+
fp.write_text(text.replace(old_string, new_string) if replace_all else text.replace(old_string, new_string, 1),
|
| 197 |
+
encoding="utf-8")
|
| 198 |
+
await workspace.sync()
|
| 199 |
+
return {"ok": True, "path": path, "replacements": n if replace_all else 1}
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
# ---------- 技能 ----------
|
| 203 |
+
async def load_skill(name: str):
|
| 204 |
+
return await skillmod.load(name)
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
async def read_skill_file(name: str, path: str):
|
| 208 |
+
return await skillmod.read_file(name, path)
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
async def install_skill(source: str):
|
| 212 |
+
return await skillmod.install(source=source)
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
# ---------- 長期記憶 ----------
|
| 216 |
+
async def save_memory(content: str, tags: str = ""):
|
| 217 |
+
mid = await store.add_memory(content.strip(), tags)
|
| 218 |
+
return {"ok": True, "id": mid}
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
async def search_memory(query: str = "", limit: int = 10):
|
| 222 |
+
rows = await store.search_memories(query, max(1, min(int(limit), 50)))
|
| 223 |
+
return [{"id": r["id"], "content": r["content"], "tags": r["tags"]} for r in rows]
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
async def delete_memory(id: int):
|
| 227 |
+
return {"deleted": await store.delete_memory(int(id))}
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
# ---------- 時間 ----------
|
| 231 |
+
async def get_current_time(timezone: str = ""):
|
| 232 |
+
tz = timezone or config.DEFAULT_TZ
|
| 233 |
+
try:
|
| 234 |
+
now = datetime.now(ZoneInfo(tz))
|
| 235 |
+
except Exception:
|
| 236 |
+
return {"error": f"未知時區: {tz}"}
|
| 237 |
+
return {"timezone": tz, "datetime": now.isoformat(), "weekday": now.strftime("%A")}
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def _fn(name, desc, props, required):
|
| 241 |
+
return {"type": "function", "function": {
|
| 242 |
+
"name": name, "description": desc,
|
| 243 |
+
"parameters": {"type": "object", "properties": props, "required": required}}}
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
TOOLS = {
|
| 247 |
+
"web_search": (web_search, _fn(
|
| 248 |
+
"web_search", "搜尋網路,回傳標題、網址、摘要。需要最新資訊時使用。",
|
| 249 |
+
{"query": {"type": "string", "description": "搜尋關鍵字"},
|
| 250 |
+
"max_results": {"type": "integer", "description": "結果數量,1-10,預設 5"}},
|
| 251 |
+
["query"])),
|
| 252 |
+
"fetch_url": (fetch_url, _fn(
|
| 253 |
+
"fetch_url", "讀取��頁並回傳純文字內容。",
|
| 254 |
+
{"url": {"type": "string"},
|
| 255 |
+
"max_chars": {"type": "integer", "description": "最多回傳字數,預設 8000"}},
|
| 256 |
+
["url"])),
|
| 257 |
+
"list_files": (list_files, _fn(
|
| 258 |
+
"list_files", "列出專案資料夾(或其子目錄)裡的檔案和大小。",
|
| 259 |
+
{"path": {"type": "string", "description": "相對路徑,預設 ."},
|
| 260 |
+
"max_entries": {"type": "integer"}}, [])),
|
| 261 |
+
"read_file": (read_file, _fn(
|
| 262 |
+
"read_file", "讀取專案裡的文字檔,回傳帶行號的內容。大檔案用 start_line / max_lines 分段讀。",
|
| 263 |
+
{"path": {"type": "string"}, "start_line": {"type": "integer"}, "max_lines": {"type": "integer"}},
|
| 264 |
+
["path"])),
|
| 265 |
+
"write_file": (write_file, _fn(
|
| 266 |
+
"write_file", "建立或整個覆寫專案裡的檔案(自動建立目錄、自動保存)。",
|
| 267 |
+
{"path": {"type": "string"}, "content": {"type": "string"}}, ["path", "content"])),
|
| 268 |
+
"edit_file": (edit_file, _fn(
|
| 269 |
+
"edit_file", "精確替換檔案中的一段文字。old_string 必須和原文完全一致且唯一(不含行號前綴)。",
|
| 270 |
+
{"path": {"type": "string"}, "old_string": {"type": "string"}, "new_string": {"type": "string"},
|
| 271 |
+
"replace_all": {"type": "boolean"}}, ["path", "old_string", "new_string"])),
|
| 272 |
+
"run_python": (run_python, _fn(
|
| 273 |
+
"run_python", "在沙盒中執行 Python 3 程式碼,回傳 stdout/stderr。用 print() 輸出結果。"
|
| 274 |
+
"可用 numpy、pandas、requests。工作目錄是專案資料夾,產生的檔案會自動保存。",
|
| 275 |
+
{"code": {"type": "string"},
|
| 276 |
+
"timeout": {"type": "integer", "description": "秒數,預設 30,最多 300"}},
|
| 277 |
+
["code"])),
|
| 278 |
+
"run_shell": (run_shell, _fn(
|
| 279 |
+
"run_shell", "在沙盒執行 bash 指令(可用 python、node、npx、uvx、curl、git),回傳輸出。"
|
| 280 |
+
"用來執行技能裡的腳本或安裝臨時套件(pip install --user)。",
|
| 281 |
+
{"command": {"type": "string"},
|
| 282 |
+
"timeout": {"type": "integer", "description": "秒數,預設 60,最多 600"}},
|
| 283 |
+
["command"])),
|
| 284 |
+
"load_skill": (load_skill, _fn(
|
| 285 |
+
"load_skill", "載入一個已安裝技能的完整說明(SKILL.md)和檔案清單。處理符合技能描述的任務前必須先載入。",
|
| 286 |
+
{"name": {"type": "string"}}, ["name"])),
|
| 287 |
+
"read_skill_file": (read_skill_file, _fn(
|
| 288 |
+
"read_skill_file", "讀取技能資料夾裡的其他檔案(參考文件、範本、腳本)。",
|
| 289 |
+
{"name": {"type": "string"}, "path": {"type": "string", "description": "相對於技能資料夾的路徑"}},
|
| 290 |
+
["name", "path"])),
|
| 291 |
+
"install_skill": (install_skill, _fn(
|
| 292 |
+
"install_skill", "從 GitHub 資料夾網址或 SKILL.md 網址安裝技能。只在使用者明確要求安裝時使用。",
|
| 293 |
+
{"source": {"type": "string"}}, ["source"])),
|
| 294 |
+
"save_memory": (save_memory, _fn(
|
| 295 |
+
"save_memory", "把關於使用者的長期資訊存入記憶(偏好、事實、計劃)。",
|
| 296 |
+
{"content": {"type": "string", "description": "一句完整的事實"},
|
| 297 |
+
"tags": {"type": "string", "description": "逗號分隔的標籤,選填"}},
|
| 298 |
+
["content"])),
|
| 299 |
+
"search_memory": (search_memory, _fn(
|
| 300 |
+
"search_memory", "用關鍵字搜尋長期記憶(空白分隔多個關鍵字)。",
|
| 301 |
+
{"query": {"type": "string"}, "limit": {"type": "integer"}}, [])),
|
| 302 |
+
"delete_memory": (delete_memory, _fn(
|
| 303 |
+
"delete_memory", "依 id 刪除一條過時或錯誤的記憶。",
|
| 304 |
+
{"id": {"type": "integer"}}, ["id"])),
|
| 305 |
+
"get_current_time": (get_current_time, _fn(
|
| 306 |
+
"get_current_time", "取得目前日期時間。",
|
| 307 |
+
{"timezone": {"type": "string", "description": "IANA 時區,如 Asia/Hong_Kong"}}, [])),
|
| 308 |
+
}
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
def tool_schemas() -> list[dict]:
|
| 312 |
+
disabled = set()
|
| 313 |
+
if not config.ENABLE_PYTHON_TOOL:
|
| 314 |
+
disabled.add("run_python")
|
| 315 |
+
if not config.ENABLE_SHELL_TOOL:
|
| 316 |
+
disabled.add("run_shell")
|
| 317 |
+
builtin = [schema for name, (_, schema) in TOOLS.items() if name not in disabled]
|
| 318 |
+
return builtin + mcp.schemas
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
async def execute_tool(name: str, arguments: str) -> str:
|
| 322 |
+
if name not in TOOLS and name not in mcp.tool_map:
|
| 323 |
+
return json.dumps({"error": f"未知工具: {name}"}, ensure_ascii=False)
|
| 324 |
+
try:
|
| 325 |
+
args = json.loads(arguments) if arguments and arguments.strip() else {}
|
| 326 |
+
if not isinstance(args, dict):
|
| 327 |
+
raise ValueError("參數必須是 JSON 物件")
|
| 328 |
+
except Exception as e:
|
| 329 |
+
return json.dumps({"error": f"參數不是合法 JSON: {e}"}, ensure_ascii=False)
|
| 330 |
+
try:
|
| 331 |
+
if name in mcp.tool_map:
|
| 332 |
+
result = await mcp.call(name, args)
|
| 333 |
+
else:
|
| 334 |
+
result = await TOOLS[name][0](**args)
|
| 335 |
+
except asyncio.TimeoutError:
|
| 336 |
+
result = {"error": "工具執行逾時"}
|
| 337 |
+
except TypeError as e:
|
| 338 |
+
result = {"error": f"參數錯誤: {e}"}
|
| 339 |
+
except Exception as e:
|
| 340 |
+
result = {"error": f"{type(e).__name__}: {e}"}
|
| 341 |
+
text = json.dumps(result, ensure_ascii=False)
|
| 342 |
+
return text[:20000] + ("…(已截斷)" if len(text) > 20000 else "")
|
app/workspace.py
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""專案工作區:每個專案一個資料夾,內容持久化在 Turso(project_files 表)。
|
| 2 |
+
|
| 3 |
+
- 開始對話時:把專案檔案從 Turso 還原到 WORKDIR/projects/<id>/(容器重啟後也能恢復)
|
| 4 |
+
- 每次工具改動檔案後:掃描資料夾,把新增/修改/刪除同步回 Turso
|
| 5 |
+
- 沒有專案的對話用 WORKDIR/scratch(不持久化)
|
| 6 |
+
"""
|
| 7 |
+
import asyncio
|
| 8 |
+
import base64
|
| 9 |
+
import contextvars
|
| 10 |
+
import hashlib
|
| 11 |
+
import io
|
| 12 |
+
import logging
|
| 13 |
+
import os
|
| 14 |
+
import zipfile
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
|
| 17 |
+
from . import config
|
| 18 |
+
from . import db as store
|
| 19 |
+
|
| 20 |
+
log = logging.getLogger("workspace")
|
| 21 |
+
|
| 22 |
+
# 不同步的目錄(依賴、快取、虛擬環境):重裝即可,不值得存進資料庫
|
| 23 |
+
SKIP_DIRS = {"node_modules", ".git", "__pycache__", ".venv", "venv", ".mypy_cache", ".pytest_cache",
|
| 24 |
+
".next", "dist", "build", ".cache", ".npm", ".ruff_cache", "target"}
|
| 25 |
+
MAX_FILE = config.PROJECT_MAX_FILE_MB * 1024 * 1024
|
| 26 |
+
MAX_TOTAL = config.PROJECT_MAX_TOTAL_MB * 1024 * 1024
|
| 27 |
+
|
| 28 |
+
current_project: contextvars.ContextVar[str | None] = contextvars.ContextVar("current_project", default=None)
|
| 29 |
+
_snapshots: dict[str, dict[str, str]] = {} # project_id -> {path: sha1}
|
| 30 |
+
_locks: dict[str, asyncio.Lock] = {}
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def project_dir(pid: str | None) -> Path:
|
| 34 |
+
d = Path(config.WORKDIR) / ("projects/" + pid if pid else "scratch")
|
| 35 |
+
d.mkdir(parents=True, exist_ok=True)
|
| 36 |
+
return d
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def current_dir() -> Path:
|
| 40 |
+
return project_dir(current_project.get())
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def safe_path(rel: str) -> Path:
|
| 44 |
+
"""把相對路徑解析到目前工作區內,防止跳出資料夾。"""
|
| 45 |
+
root = current_dir().resolve()
|
| 46 |
+
p = (root / (rel or ".").lstrip("/")).resolve()
|
| 47 |
+
if p != root and root not in p.parents:
|
| 48 |
+
raise ValueError(f"路徑超出專案資料夾:{rel}")
|
| 49 |
+
return p
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def _scan(root: Path) -> dict[str, tuple[str, bytes]]:
|
| 53 |
+
out = {}
|
| 54 |
+
for dirpath, dirnames, filenames in os.walk(root):
|
| 55 |
+
dirnames[:] = [d for d in dirnames if d not in SKIP_DIRS]
|
| 56 |
+
for fn in filenames:
|
| 57 |
+
fp = Path(dirpath) / fn
|
| 58 |
+
try:
|
| 59 |
+
if fp.is_symlink() or fp.stat().st_size > MAX_FILE:
|
| 60 |
+
continue
|
| 61 |
+
data = fp.read_bytes()
|
| 62 |
+
except OSError:
|
| 63 |
+
continue
|
| 64 |
+
out[fp.relative_to(root).as_posix()] = (hashlib.sha1(data).hexdigest(), data)
|
| 65 |
+
return out
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
async def restore(pid: str):
|
| 69 |
+
"""從 Turso 還原專案檔案到磁碟(每個容器生命週期只做一次)。"""
|
| 70 |
+
if pid in _snapshots:
|
| 71 |
+
return
|
| 72 |
+
lock = _locks.setdefault(pid, asyncio.Lock())
|
| 73 |
+
async with lock:
|
| 74 |
+
if pid in _snapshots:
|
| 75 |
+
return
|
| 76 |
+
root = project_dir(pid)
|
| 77 |
+
snap = {}
|
| 78 |
+
for r in await store.list_project_files(pid, with_data=True):
|
| 79 |
+
fp = root / r["path"]
|
| 80 |
+
fp.parent.mkdir(parents=True, exist_ok=True)
|
| 81 |
+
data = base64.b64decode(r["data"] or "")
|
| 82 |
+
fp.write_bytes(data)
|
| 83 |
+
snap[r["path"]] = hashlib.sha1(data).hexdigest()
|
| 84 |
+
_snapshots[pid] = snap
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
async def sync(pid: str | None = None) -> dict:
|
| 88 |
+
"""把磁碟上的改動同步回 Turso,回傳 {changed, deleted}。"""
|
| 89 |
+
pid = pid or current_project.get()
|
| 90 |
+
if not pid:
|
| 91 |
+
return {"changed": [], "deleted": []}
|
| 92 |
+
await restore(pid)
|
| 93 |
+
async with _locks.setdefault(pid, asyncio.Lock()):
|
| 94 |
+
files = await asyncio.to_thread(_scan, project_dir(pid))
|
| 95 |
+
total = sum(len(d) for _, d in files.values())
|
| 96 |
+
if total > MAX_TOTAL:
|
| 97 |
+
log.warning("專案 %s 超過 %dMB,只同步較小的檔案", pid, config.PROJECT_MAX_TOTAL_MB)
|
| 98 |
+
old = _snapshots.get(pid, {})
|
| 99 |
+
changed = [p for p, (h, _) in files.items() if old.get(p) != h]
|
| 100 |
+
deleted = [p for p in old if p not in files]
|
| 101 |
+
budget = MAX_TOTAL
|
| 102 |
+
stmts = []
|
| 103 |
+
for p in sorted(files, key=lambda x: len(files[x][1])):
|
| 104 |
+
budget -= len(files[p][1])
|
| 105 |
+
if p in changed and budget >= 0:
|
| 106 |
+
stmts.append(store.upsert_file_stmt(pid, p, base64.b64encode(files[p][1]).decode(),
|
| 107 |
+
len(files[p][1])))
|
| 108 |
+
elif p in changed:
|
| 109 |
+
changed.remove(p)
|
| 110 |
+
stmts += [store.delete_file_stmt(pid, p) for p in deleted]
|
| 111 |
+
for i in range(0, len(stmts), 20):
|
| 112 |
+
await store.db.batch(stmts[i:i + 20])
|
| 113 |
+
new_snap = dict(old)
|
| 114 |
+
for p in changed:
|
| 115 |
+
new_snap[p] = files[p][0]
|
| 116 |
+
for p in deleted:
|
| 117 |
+
new_snap.pop(p, None)
|
| 118 |
+
_snapshots[pid] = new_snap
|
| 119 |
+
if stmts:
|
| 120 |
+
await store.touch_project(pid)
|
| 121 |
+
return {"changed": changed, "deleted": deleted}
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def tree(pid: str | None, limit: int = 300) -> list[str]:
|
| 125 |
+
root = project_dir(pid)
|
| 126 |
+
out = []
|
| 127 |
+
for dirpath, dirnames, filenames in os.walk(root):
|
| 128 |
+
dirnames[:] = sorted(d for d in dirnames if d not in SKIP_DIRS)
|
| 129 |
+
for fn in sorted(filenames):
|
| 130 |
+
out.append((Path(dirpath) / fn).relative_to(root).as_posix())
|
| 131 |
+
if len(out) >= limit:
|
| 132 |
+
return out
|
| 133 |
+
return out
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
async def write_upload(pid: str, path: str, data: bytes):
|
| 137 |
+
await restore(pid)
|
| 138 |
+
token = current_project.set(pid)
|
| 139 |
+
try:
|
| 140 |
+
fp = safe_path(path)
|
| 141 |
+
fp.parent.mkdir(parents=True, exist_ok=True)
|
| 142 |
+
fp.write_bytes(data)
|
| 143 |
+
finally:
|
| 144 |
+
current_project.reset(token)
|
| 145 |
+
await sync(pid)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
async def delete_path(pid: str, path: str):
|
| 149 |
+
await restore(pid)
|
| 150 |
+
token = current_project.set(pid)
|
| 151 |
+
try:
|
| 152 |
+
fp = safe_path(path)
|
| 153 |
+
if fp.is_file():
|
| 154 |
+
fp.unlink()
|
| 155 |
+
finally:
|
| 156 |
+
current_project.reset(token)
|
| 157 |
+
await sync(pid)
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
async def read_bytes(pid: str, path: str) -> bytes:
|
| 161 |
+
await restore(pid)
|
| 162 |
+
token = current_project.set(pid)
|
| 163 |
+
try:
|
| 164 |
+
return safe_path(path).read_bytes()
|
| 165 |
+
finally:
|
| 166 |
+
current_project.reset(token)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
async def zip_project(pid: str) -> bytes:
|
| 170 |
+
await restore(pid)
|
| 171 |
+
root = project_dir(pid)
|
| 172 |
+
buf = io.BytesIO()
|
| 173 |
+
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as z:
|
| 174 |
+
for rel in tree(pid, limit=100000):
|
| 175 |
+
z.write(root / rel, rel)
|
| 176 |
+
return buf.getvalue()
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def forget(pid: str):
|
| 180 |
+
import shutil
|
| 181 |
+
shutil.rmtree(project_dir(pid), ignore_errors=True)
|
| 182 |
+
_snapshots.pop(pid, None)
|
requirements.txt
CHANGED
|
@@ -1,5 +1,12 @@
|
|
| 1 |
-
fastapi=
|
| 2 |
-
uvicorn[standard]=
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fastapi>=0.111
|
| 2 |
+
uvicorn[standard]>=0.30
|
| 3 |
+
httpx>=0.27
|
| 4 |
+
beautifulsoup4>=4.12
|
| 5 |
+
pydantic>=2.7
|
| 6 |
+
tzdata
|
| 7 |
+
ddgs>=9.0
|
| 8 |
+
mcp>=1.12,<2
|
| 9 |
+
pyyaml>=6
|
| 10 |
+
numpy
|
| 11 |
+
pandas
|
| 12 |
+
requests
|