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
4d5692f
0299897
 
4d5692f
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
"""Agent 可用的工具。新增工具:寫一個 async 函數,再在 TOOLS 裡登記 schema 即可。"""
import asyncio
import ipaddress
import json
import os
import resource
import socket
import sys
import tempfile
from datetime import datetime
from urllib.parse import urlparse
from zoneinfo import ZoneInfo

import httpx
from bs4 import BeautifulSoup

from . import config
from . import db as store
from . import skills as skillmod
from . import procs
from . import workspace
from .mcp_client import manager as mcp

UA = ("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
      "(KHTML, like Gecko) Chrome/126.0 Safari/537.36")


# ---------- 網路搜尋 ----------
async def web_search(query: str, max_results: int = 5):
    max_results = max(1, min(int(max_results), 10))
    async with httpx.AsyncClient(timeout=20, headers={"User-Agent": UA}, follow_redirects=True) as c:
        if config.TAVILY_API_KEY:
            r = await c.post(
                "https://api.tavily.com/search",
                headers={"Authorization": f"Bearer {config.TAVILY_API_KEY}"},
                json={"api_key": config.TAVILY_API_KEY, "query": query, "max_results": max_results},
            )
            r.raise_for_status()
            return [{"title": x.get("title"), "url": x.get("url"), "snippet": x.get("content")}
                    for x in r.json().get("results", [])]
    # 沒有 Tavily:用 ddgs(多後端元搜尋,HF 等機房 IP 也能用)
    def _ddgs():
        from ddgs import DDGS
        return DDGS().text(query, max_results=max_results) or []
    rows = await asyncio.to_thread(_ddgs)
    out = [{"title": x.get("title"), "url": x.get("href"), "snippet": x.get("body")} for x in rows]
    return out or {"error": "沒有搜尋結果(可設定 TAVILY_API_KEY 換更穩的搜尋)"}


# ---------- 讀網頁 ----------
def _is_public_host(host: str) -> bool:
    try:
        infos = socket.getaddrinfo(host, None)
    except socket.gaierror:
        return False
    for info in infos:
        ip = ipaddress.ip_address(info[4][0])
        if ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_reserved or ip.is_multicast:
            return False
    return True


async def fetch_url(url: str, max_chars: int = 8000):
    p = urlparse(url)
    if p.scheme not in ("http", "https") or not p.hostname:
        return {"error": "只支援 http/https 網址"}
    if not await asyncio.to_thread(_is_public_host, p.hostname):
        return {"error": "拒絕訪問內網或無法解析的位址"}
    async with httpx.AsyncClient(timeout=25, headers={"User-Agent": UA}, follow_redirects=True) as c:
        r = await c.get(url)
    ct = r.headers.get("content-type", "").lower()
    if ct and not any(k in ct for k in ("text", "html", "json", "xml")):
        return {"url": str(r.url), "status": r.status_code, "error": f"不支援的內容類型: {ct}"}
    title = ""
    if "html" in ct or r.text.lstrip()[:15].lower().startswith(("<!doctype", "<html")):
        soup = BeautifulSoup(r.text, "html.parser")
        for t in soup(["script", "style", "noscript", "nav", "footer", "header", "aside", "form", "svg", "iframe"]):
            t.decompose()
        title = soup.title.get_text(strip=True) if soup.title else ""
        text = soup.get_text("\n", strip=True)
    else:
        text = r.text
    text = "\n".join(line for line in text.splitlines() if line.strip())
    max_chars = max(500, min(int(max_chars), 30000))
    return {"url": str(r.url), "status": r.status_code, "title": title,
            "content": text[:max_chars], "truncated": len(text) > max_chars}


# ---------- 執行 Python ----------
def _limits(mem_gb: int, timeout: int):
    def apply():
        os.setsid()  # 自成一組,停止或逾時時連子孫程序一起結束
        if mem_gb > 0:
            mem = mem_gb * 1024 ** 3
            resource.setrlimit(resource.RLIMIT_AS, (mem, mem))
        cpu = timeout * 4 + 60  # 多核心程式的 CPU 時間會比牆鐘時間多
        resource.setrlimit(resource.RLIMIT_CPU, (cpu, cpu))
    return apply


def _kill(proc):
    try:
        os.killpg(proc.pid, 9)
    except (ProcessLookupError, PermissionError):
        try:
            proc.kill()
        except ProcessLookupError:
            pass


def _sandbox_env() -> dict:
    # 乾淨的環境變數:子程序看不到 API key / 資料庫 token
    home = os.path.join(config.WORKDIR, ".home")
    os.makedirs(home, exist_ok=True)
    return {"PATH": f"{home}/.local/bin:" + os.environ.get("PATH", ""), "HOME": home, "MPLBACKEND": "Agg",
            "PYTHONIOENCODING": "utf-8", "LANG": "C.UTF-8", "SKILLS_DIR": config.SKILLS_DIR}


async def _run(argv: list[str], timeout: int, mem_gb: int) -> dict:
    proc = await asyncio.create_subprocess_exec(
        *argv, cwd=str(workspace.current_dir()), env=_sandbox_env(),
        stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, preexec_fn=_limits(mem_gb, timeout),
    )
    try:
        out, err = await asyncio.wait_for(proc.communicate(), timeout)
    except asyncio.CancelledError:  # 使用者按停止:結束子程序
        _kill(proc)
        await asyncio.shield(proc.wait())
        raise
    except asyncio.TimeoutError:
        _kill(proc)
        await proc.wait()
        await workspace.sync()
        return {"error": f"執行逾時({timeout} 秒)"}
    synced = await workspace.sync()
    res = {"exit_code": proc.returncode,
           "stdout": out.decode(errors="replace")[-10000:],
           "stderr": err.decode(errors="replace")[-5000:]}
    if synced["changed"] or synced["deleted"]:
        res["files_saved"] = synced["changed"][:50]
        res["files_deleted"] = synced["deleted"][:50]
    return res


async def run_python(code: str, timeout: int = 30):
    if not config.ENABLE_PYTHON_TOOL:
        return {"error": "Python 工具已停用"}
    timeout = max(1, min(int(timeout), config.MAX_TOOL_TIMEOUT))
    with tempfile.NamedTemporaryFile("w", suffix=".py", delete=False, encoding="utf-8") as f:
        f.write(code)
        path = f.name
    try:
        return await _run([sys.executable, "-I", path], timeout, config.TOOL_MEM_GB)
    finally:
        os.unlink(path)


async def run_shell(command: str, timeout: int = 60):
    if not config.ENABLE_SHELL_TOOL:
        return {"error": "Shell 工具已停用"}
    timeout = max(1, min(int(timeout), config.MAX_TOOL_TIMEOUT))
    return await _run(["bash", "-c", command], timeout, config.TOOL_MEM_GB)


# ---------- 背景程序 ----------
async def start_process(command: str, name: str = ""):
    if not config.ENABLE_SHELL_TOOL:
        return {"error": "Shell 工具已停用"}
    env = {**_sandbox_env(), "HOST": "0.0.0.0"}
    res = await procs.start(command, name or None, env, _limits(config.TOOL_MEM_GB, 10 ** 6))
    if res.get("ports"):
        res["hint"] = (f"用 run_shell 跑 curl -s http://127.0.0.1:{res['ports'][0]}/ 測試;"
                       "使用者可以在介面的「程序」面板打開預覽。")
    return res


async def process_logs(name: str, tail: int = 200):
    return procs.logs(name, tail)


async def stop_process(name: str):
    res = await procs.stop(name)
    await _sync_quiet()
    return res


async def list_processes():
    return {"processes": procs.listing()}


# ---------- 專案檔案 ----------
async def list_files(path: str = ".", max_entries: int = 300):
    root = workspace.current_dir()
    base = workspace.safe_path(path)
    if not base.exists():
        return {"error": f"不存在:{path}"}
    out = []
    for rel in workspace.tree(workspace.current_project.get(), limit=100000):
        full = root / rel
        if base == root or base in full.parents:
            out.append(f"{rel}  ({full.stat().st_size} B)")
            if len(out) >= max_entries:
                out.append("…(已截斷,請指定子目錄)")
                break
    return {"root": str(root), "files": out}


async def read_file(path: str, start_line: int = 1, max_lines: int = 400):
    fp = workspace.safe_path(path)
    if not fp.is_file():
        return {"error": f"不是檔案:{path}"}
    try:
        lines = fp.read_text(encoding="utf-8").splitlines()
    except UnicodeDecodeError:
        return {"error": "二進位檔,無法以文字讀取", "size": fp.stat().st_size}
    start = max(1, int(start_line))
    chunk = lines[start - 1:start - 1 + max(1, min(int(max_lines), 2000))]
    return {"path": path, "total_lines": len(lines), "start_line": start,
            "content": "\n".join(f"{start + i:>5}| {ln}" for i, ln in enumerate(chunk))}


def _where() -> str:
    return "專案(已永久保存)" if workspace.current_project.get() else "暫存區(這個對話不屬於任何專案,重啟後消失)"


async def _sync_quiet() -> str | None:
    """同步到資料庫;慢或失敗不卡住 agent(檔案已在磁碟上,下次改動會再同步)。"""
    try:
        await asyncio.wait_for(workspace.sync(), 60)
    except Exception as e:  # noqa: BLE001
        return f"檔案已寫入,但同步到資料庫失敗({type(e).__name__}),下次改動時會重試"
    return None


async def write_file(path: str, content: str, append: bool = False):
    fp = workspace.safe_path(path)
    fp.parent.mkdir(parents=True, exist_ok=True)
    with open(fp, "a" if append else "w", encoding="utf-8") as f:
        f.write(content)
    res = {"ok": True, "path": path, "bytes": fp.stat().st_size, "saved_in": _where()}
    if warn := await _sync_quiet():
        res["warning"] = warn
    return res


async def edit_file(path: str, old_string: str, new_string: str, replace_all: bool = False):
    fp = workspace.safe_path(path)
    if not fp.is_file():
        return {"error": f"不是檔案:{path}"}
    text = fp.read_text(encoding="utf-8")
    n = text.count(old_string)
    if n == 0:
        return {"error": "找不到 old_string(要和檔案內容完全一致,包括縮排)"}
    if n > 1 and not replace_all:
        return {"error": f"old_string 出現 {n} 次,請多帶幾行上下文讓它唯一,或設 replace_all=true"}
    fp.write_text(text.replace(old_string, new_string) if replace_all else text.replace(old_string, new_string, 1),
                  encoding="utf-8")
    res = {"ok": True, "path": path, "replacements": n if replace_all else 1}
    if warn := await _sync_quiet():
        res["warning"] = warn
    return res


# ---------- 技能 ----------
async def load_skill(name: str):
    return await skillmod.load(name)


async def read_skill_file(name: str, path: str):
    return await skillmod.read_file(name, path)


async def install_skill(source: str):
    return await skillmod.install(source=source)


# ---------- 長期記憶 ----------
async def save_memory(content: str, tags: str = ""):
    mid = await store.add_memory(content.strip(), tags)
    return {"ok": True, "id": mid}


async def search_memory(query: str = "", limit: int = 10):
    rows = await store.search_memories(query, max(1, min(int(limit), 50)))
    return [{"id": r["id"], "content": r["content"], "tags": r["tags"]} for r in rows]


async def delete_memory(id: int):
    return {"deleted": await store.delete_memory(int(id))}


# ---------- 時間 ----------
async def get_current_time(timezone: str = ""):
    tz = timezone or config.DEFAULT_TZ
    try:
        now = datetime.now(ZoneInfo(tz))
    except Exception:
        return {"error": f"未知時區: {tz}"}
    return {"timezone": tz, "datetime": now.isoformat(), "weekday": now.strftime("%A")}


def _fn(name, desc, props, required):
    return {"type": "function", "function": {
        "name": name, "description": desc,
        "parameters": {"type": "object", "properties": props, "required": required}}}


TOOLS = {
    "web_search": (web_search, _fn(
        "web_search", "搜尋網路,回傳標題、網址、摘要。需要最新資訊時使用。",
        {"query": {"type": "string", "description": "搜尋關鍵字"},
         "max_results": {"type": "integer", "description": "結果數量,1-10,預設 5"}},
        ["query"])),
    "fetch_url": (fetch_url, _fn(
        "fetch_url", "讀取網頁並回傳純文字內容。",
        {"url": {"type": "string"},
         "max_chars": {"type": "integer", "description": "最多回傳字數,預設 8000"}},
        ["url"])),
    "list_files": (list_files, _fn(
        "list_files", "列出專案資料夾(或其子目錄)裡的檔案和大小。",
        {"path": {"type": "string", "description": "相對路徑,預設 ."},
         "max_entries": {"type": "integer"}}, [])),
    "read_file": (read_file, _fn(
        "read_file", "讀取專案裡的文字檔,回傳帶行號的內容。大檔案用 start_line / max_lines 分段讀。",
        {"path": {"type": "string"}, "start_line": {"type": "integer"}, "max_lines": {"type": "integer"}},
        ["path"])),
    "write_file": (write_file, _fn(
        "write_file", "建立或整個覆寫專案裡的檔案(自動建立目錄、自動保存)。"
                      "很長的檔案(超過約 300 行)請分段寫:第一段正常寫,之後每段設 append=true 接在後面。",
        {"path": {"type": "string"}, "content": {"type": "string"},
         "append": {"type": "boolean", "description": "true=接在檔案結尾,不覆寫"}}, ["path", "content"])),
    "edit_file": (edit_file, _fn(
        "edit_file", "精確替換檔案中的一段文字。old_string 必須和原文完全一致且唯一(不含行號前綴)。",
        {"path": {"type": "string"}, "old_string": {"type": "string"}, "new_string": {"type": "string"},
         "replace_all": {"type": "boolean"}}, ["path", "old_string", "new_string"])),
    "run_python": (run_python, _fn(
        "run_python", "在沙盒中執行 Python 3 程式碼,回傳 stdout/stderr。用 print() 輸出結果。"
                      "已裝 numpy、pandas、scipy、matplotlib、pillow、openpyxl、python-docx、python-pptx、pypdf、requests 等。"
                      "工作目錄是專案資料夾,產生的檔案會自動保存。",
        {"code": {"type": "string"},
         "timeout": {"type": "integer", "description": f"秒數,預設 30,最多 {config.MAX_TOOL_TIMEOUT}"}},
        ["code"])),
    "run_shell": (run_shell, _fn(
        "run_shell", "在沙盒執行 bash 指令(可用 python、node、npm、npx、uvx、git、curl、gcc、make、ffmpeg、"
                     "libreoffice(soffice)、pdftotext、sqlite3、jq、rg),回傳輸出。"
                     "用來跑測試、建置、執行技能腳本或安裝套件(pip install --user、npm install)。",
        {"command": {"type": "string"},
         "timeout": {"type": "integer", "description": f"秒數,預設 60,最多 {config.MAX_TOOL_TIMEOUT}"}},
        ["command"])),
    "load_skill": (load_skill, _fn(
        "load_skill", "載入一個已安裝技能的完整說明(SKILL.md)和檔案清單。處理符合技能描述的任務前必須先載入。",
        {"name": {"type": "string"}}, ["name"])),
    "read_skill_file": (read_skill_file, _fn(
        "read_skill_file", "讀取技能資料夾裡的其他檔案(參考文件、範本、腳本)。",
        {"name": {"type": "string"}, "path": {"type": "string", "description": "相對於技能資料夾的路徑"}},
        ["name", "path"])),
    "install_skill": (install_skill, _fn(
        "install_skill", "從 GitHub 資料夾網址或 SKILL.md 網址安裝技能。只在使用者明確要求安裝時使用。",
        {"source": {"type": "string"}}, ["source"])),
    "save_memory": (save_memory, _fn(
        "save_memory", "把關於使用者的長期資訊存入記憶(偏好、事實、計劃)。",
        {"content": {"type": "string", "description": "一句完整的事實"},
         "tags": {"type": "string", "description": "逗號分隔的標籤,選填"}},
        ["content"])),
    "search_memory": (search_memory, _fn(
        "search_memory", "用關鍵字搜尋長期記憶(空白分隔多個關鍵字)。",
        {"query": {"type": "string"}, "limit": {"type": "integer"}}, [])),
    "delete_memory": (delete_memory, _fn(
        "delete_memory", "依 id 刪除一條過時或錯誤的記憶。",
        {"id": {"type": "integer"}}, ["id"])),
    "start_process": (start_process, _fn(
        "start_process", "在背景啟動長時間執行的程序(開發伺服器、npm run dev、watch、資料庫等),立刻返回,不會卡住。"
                         "回傳最初幾秒的輸出和偵測到的埠號。之後用 process_logs 看輸出、run_shell 用 curl 測試、stop_process 停止。"
                         "伺服器請監聽 0.0.0.0 或 127.0.0.1,埠號用 3000–9999 之間(7860 已被本程式使用)。",
        {"command": {"type": "string"}, "name": {"type": "string", "description": "程序名稱,之後查看/停止用"}}, ["command"])),
    "process_logs": (process_logs, _fn(
        "process_logs", "查看背景程序的最新輸出和狀態。",
        {"name": {"type": "string"}, "tail": {"type": "integer", "description": "最後幾行,預設 200"}}, ["name"])),
    "stop_process": (stop_process, _fn(
        "stop_process", "停止背景程序(連同它的子程序)。", {"name": {"type": "string"}}, ["name"])),
    "list_processes": (list_processes, _fn("list_processes", "列出所有背景程序。", {}, [])),
    "get_current_time": (get_current_time, _fn(
        "get_current_time", "取得目前日期時間。",
        {"timezone": {"type": "string", "description": "IANA 時區,如 Asia/Hong_Kong"}}, [])),
}


def tool_schemas() -> list[dict]:
    disabled = set()
    if not config.ENABLE_PYTHON_TOOL:
        disabled.add("run_python")
    if not config.ENABLE_SHELL_TOOL:
        disabled |= {"run_shell", "start_process", "process_logs", "stop_process", "list_processes"}
    builtin = [schema for name, (_, schema) in TOOLS.items() if name not in disabled]
    return builtin + mcp.schemas


async def execute_tool(name: str, arguments: str) -> str:
    if name not in TOOLS and name not in mcp.tool_map:
        return json.dumps({"error": f"未知工具: {name}"}, ensure_ascii=False)
    try:
        args = json.loads(arguments) if arguments and arguments.strip() else {}
        if not isinstance(args, dict):
            raise ValueError("參數必須是 JSON 物件")
        if args.get("_truncated"):
            raise ValueError("模型輸出到了長度上限,參數被截斷")
        if "_invalid_arguments" in args:
            return json.dumps({"error": "你這次給的工具參數不是合法 JSON,工具沒有執行。請重新呼叫,"
                                        "arguments 必須是單一 JSON 物件(雙引號、不要包 ``` 或加說明文字)。"
                                        "內容很長時分段寫:write_file 寫第一段,再用 append=true 接上。",
                               "received": args["_invalid_arguments"][:500]}, ensure_ascii=False)
    except Exception as e:
        return json.dumps({"error": f"參數不是合法 JSON: {e}。很可能是內容太長被截斷:請把檔案分成較小的段落,"
                                     "用 write_file 寫第一段,再用 append=true 逐段接上。"}, ensure_ascii=False)
    try:
        if name in mcp.tool_map:
            result = await mcp.call(name, args)
        else:
            result = await TOOLS[name][0](**args)
    except asyncio.TimeoutError:
        result = {"error": "工具執行逾時"}
    except TypeError as e:
        result = {"error": f"參數錯誤: {e}"}
    except Exception as e:
        result = {"error": f"{type(e).__name__}: {e}"}
    text = json.dumps(result, ensure_ascii=False)
    return text[:20000] + ("…(已截斷)" if len(text) > 20000 else "")