Upload 19 files
Browse files- README.md +137 -5
- app/agent.py +45 -32
- app/config.py +3 -1
- app/db.py +14 -0
- app/main.py +98 -11
- app/runs.py +101 -0
- app/static/index.html +0 -0
- app/static/marked.min.js +6 -0
- app/static/purify.min.js +7 -0
- app/tools.py +4 -0
README.md
CHANGED
|
@@ -1,10 +1,142 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
colorFrom: indigo
|
| 5 |
-
colorTo:
|
| 6 |
sdk: docker
|
| 7 |
-
|
| 8 |
-
app_file: Dockerfile
|
| 9 |
pinned: false
|
| 10 |
---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: My Agent
|
| 3 |
+
emoji: 🤖
|
| 4 |
colorFrom: indigo
|
| 5 |
+
colorTo: gray
|
| 6 |
sdk: docker
|
| 7 |
+
app_port: 7860
|
|
|
|
| 8 |
pinned: false
|
| 9 |
---
|
| 10 |
+
|
| 11 |
+
# My Agent — 私人 AI Agent(HF Docker Space + Turso)
|
| 12 |
+
|
| 13 |
+
單容器、無 GPU、密碼保護的個人 AI agent。
|
| 14 |
+
|
| 15 |
+
- 後端:FastAPI,串流(SSE)回覆,多輪工具調用的 agent 循環
|
| 16 |
+
- 模型:在前端「🤖 模型」面板新增任意多個 OpenAI 相容提供商,可拉取、篩選模型;每個對話可隨時手動換模型
|
| 17 |
+
- **專案**:每個專案有自己的說明和資料夾,檔案永久存在 Turso;agent 有 list/read/write/edit 檔案工具,run_shell / run_python 直接在專案資料夾裡跑
|
| 18 |
+
- 資料庫:Turso(HTTP API,無需原生驅動),存對話、記憶、設定 —— Space 重啟不丟資料
|
| 19 |
+
- 前端:單頁 HTML,密碼登入(HMAC token,含登入失敗鎖定)
|
| 20 |
+
- 工具:網路搜尋、讀網頁、Python / Shell 沙盒、長期記憶(存/搜/刪)、目前時間
|
| 21 |
+
- **MCP**:接任意 MCP 伺服器(遠端 Streamable HTTP / SSE,或本地 npx / uvx stdio),工具自動給 agent 用
|
| 22 |
+
- **Skills**:相容 Anthropic Agent Skills(SKILL.md),可從 GitHub 一鍵安裝,也能叫 agent 自己裝
|
| 23 |
+
|
| 24 |
+
## 部署步驟
|
| 25 |
+
|
| 26 |
+
### 1. 建 Turso 資料庫
|
| 27 |
+
```bash
|
| 28 |
+
curl -sSfL https://get.tur.so/install.sh | bash
|
| 29 |
+
turso auth login
|
| 30 |
+
turso db create my-agent
|
| 31 |
+
turso db show my-agent --url # → TURSO_DATABASE_URL
|
| 32 |
+
turso db tokens create my-agent # → TURSO_AUTH_TOKEN
|
| 33 |
+
```
|
| 34 |
+
資料表會在第一次啟動時自動建立。
|
| 35 |
+
|
| 36 |
+
### 2. 建 Hugging Face Space
|
| 37 |
+
New Space → SDK 選 **Docker**(Blank)→ 硬體 CPU basic(2 vCPU / 16GB)→ 建議設為 **Private**。
|
| 38 |
+
把本專案所有檔案推上去(`git push` 或網頁上傳)。
|
| 39 |
+
|
| 40 |
+
### 3. 設定 Secrets(Space → Settings → Variables and secrets)
|
| 41 |
+
| 名稱 | 必填 | 說明 |
|
| 42 |
+
|---|---|---|
|
| 43 |
+
| `APP_SECRET` | ✅ | 前端登入密碼,建議 20+ 隨機字元 |
|
| 44 |
+
| `TURSO_DATABASE_URL` | ✅ | `libsql://xxx.turso.io` |
|
| 45 |
+
| `TURSO_AUTH_TOKEN` | ✅ | Turso token |
|
| 46 |
+
| `TAVILY_API_KEY` | | 有就用 Tavily 搜尋(較穩),否則用免費的 ddgs 元搜尋 |
|
| 47 |
+
| `DEFAULT_TZ` | | 預設 `Asia/Hong_Kong` |
|
| 48 |
+
| `MAX_AGENT_STEPS` | | 每次回覆最多工具輪數,預設 8 |
|
| 49 |
+
| `ENABLE_PYTHON_TOOL` | | 預設 `true` |
|
| 50 |
+
| `SESSION_DAYS` | | 登入有效天數,預設 30 |
|
| 51 |
+
| `ENABLE_SHELL_TOOL` | | 預設 `true` |
|
| 52 |
+
| `GITHUB_TOKEN` | | 選填,安裝私有 repo 的技能時用 |
|
| 53 |
+
| `DEFAULT_SKILLS` | | 首次啟動自動安裝的技能網址(逗號分隔),預設為一組開發技能 |
|
| 54 |
+
| 其他任意名稱 | | 給 MCP 設定裡的 `${VAR}` 引用,例如 `GITHUB_PAT`、`NOTION_TOKEN` |
|
| 55 |
+
|
| 56 |
+
### 模型(在面板裡設定,不用環境變數,也沒有任何預設)
|
| 57 |
+
左下「🤖 模型」:
|
| 58 |
+
1. 「+ 新增提供商」,填名稱、Base URL(任何 OpenAI 相容端點)和 API key(可直接填,或填 `${VAR}` 讀 Space Secrets),數量不限
|
| 59 |
+
2. 「拉取模型」取得清單,用篩選框搜(空格分隔多個關鍵字),勾選要用的;也能手動輸入模型 ID
|
| 60 |
+
3. 在頂欄下拉選單選模型。對話中切換只影響該對話(會記住);在新對話畫面切換=改預設
|
| 61 |
+
4. 只用你選的模型,不會自動切換;呼叫失敗會直接顯示錯誤,自己換模型重試
|
| 62 |
+
|
| 63 |
+
key 存在 Turso;面板上只顯示末 4 碼。
|
| 64 |
+
(模型必須支援 function / tool calling。)
|
| 65 |
+
|
| 66 |
+
### 4. 使用
|
| 67 |
+
建好後開 `https://<你的帳號>-<space名>.hf.space`,輸入 `APP_SECRET` 登入。
|
| 68 |
+
雙擊左側對話可重新命名;「🧠 記憶」可查看/刪除 agent 記住的事;「⚙️ 設定」可改系統提示詞。
|
| 69 |
+
|
| 70 |
+
## 背景執行與繼續
|
| 71 |
+
- agent 在伺服器背景執行,關掉頁面、重新整理、斷網都不會中斷;回來打開對話會自動接上進度,側欄會顯示執行中的對話
|
| 72 |
+
- 只有按送出鍵位置的「停止」才會中止(也會結束正在跑的指令)
|
| 73 |
+
- 停止、出錯或跑到步數上限時,對話底下出現「繼續執行」,點一下就從中斷處接著做,不用再打字
|
| 74 |
+
- 模型等待時間:`LLM_TIMEOUT`(預設 900 秒,指兩段輸出之間最多等多久)、`LLM_CONNECT_TIMEOUT`(預設 60);每次執行最多 `MAX_AGENT_STEPS` 輪工具調用(預設 40)
|
| 75 |
+
- 注意:HF 免費 Space 閒置太久會休眠,容器重啟時進行中的執行會中斷(已完成的步驟都已存進 Turso,可按「繼續執行」)
|
| 76 |
+
|
| 77 |
+
## 專案
|
| 78 |
+
側欄上方選專案(或「+ 新增專案…」),📁 按鈕管理:
|
| 79 |
+
- **專案說明**:技術棧、規範、目標等,專案裡每個對話的 agent 都會看到
|
| 80 |
+
- **檔案**:agent 寫的檔案、你上傳的檔案或資料夾都在這裡,可篩選、下載、刪除,或打包下載整個專案 .zip
|
| 81 |
+
- 專案資料夾就是 `run_shell` / `run_python` 的工作目錄;每次工具改動後自動同步到 Turso,Space 重啟或重建後會自動還原
|
| 82 |
+
- `node_modules`、`.git`、`.venv`、`dist`、`build` 等目錄不同步(重裝即可);單檔上限 `PROJECT_MAX_FILE_MB`(預設 5),每個專案上限 `PROJECT_MAX_TOTAL_MB`(預設 100)
|
| 83 |
+
- 不在專案裡的對話用暫存區,重啟就清空
|
| 84 |
+
- 刪除專案會刪掉它的檔案,對話保留並變成未歸類
|
| 85 |
+
|
| 86 |
+
## MCP
|
| 87 |
+
左下「MCP」→「新增 MCP 伺服器」,數量不限,每個填:
|
| 88 |
+
- 名稱、連線方式(遠端 HTTP / 遠端 SSE / 本地指令)
|
| 89 |
+
- 遠端:URL + 認證(無需認證 / Bearer Token / 自訂 Header + API Key)
|
| 90 |
+
- 本地指令:指令(npx、uvx)、參數、環境變數
|
| 91 |
+
- token 可直接填,或填 `${VAR}` 讀 Space Secrets;存好後面板只顯示末 4 碼
|
| 92 |
+
- 每個伺服器可單獨啟用/停用,卡片上會顯示連線狀態、錯誤和工具清單
|
| 93 |
+
- 已有 Claude Desktop / Cursor 的設定,可用「匯入 JSON」一次加進來
|
| 94 |
+
|
| 95 |
+
## Skills
|
| 96 |
+
左下「🧩 技能」:
|
| 97 |
+
- 貼 GitHub 資料夾網址,例如 `https://github.com/anthropics/skills/tree/main/skills/pdf`(也接受指向 SKILL.md 的 blob / raw 網址)
|
| 98 |
+
- 或直接貼上 SKILL.md 內容
|
| 99 |
+
- 也可以在對話裡說「幫我安裝這個技能 <網址>」,agent 會用 `install_skill` 自己裝
|
| 100 |
+
|
| 101 |
+
**預設技能(開發向)**:首次啟動自動安裝,之後可在技能視窗停用或刪除(刪掉的不會再裝回來):
|
| 102 |
+
- obra/superpowers:brainstorming、writing-plans、executing-plans、test-driven-development、systematic-debugging、requesting-code-review、receiving-code-review、verification-before-completion
|
| 103 |
+
- anthropics/skills:mcp-builder、frontend-design、skill-creator
|
| 104 |
+
|
| 105 |
+
想換成自己的清單,在 Secrets 設 `DEFAULT_SKILLS`(逗號分隔的 GitHub 資料夾網址);設成空字串則不裝任何預設技能。
|
| 106 |
+
|
| 107 |
+
運作方式:系統提示只列技能名稱和描述;遇到相關任務時 agent 先 `load_skill` 讀完整說明,需要時 `read_skill_file` 讀附檔,用 `run_shell` 執行技能裡的腳本。技能存在 Turso,容器重啟時自動寫回磁碟。下載走 GitHub 壓縮包,不受 API 限流影響。
|
| 108 |
+
|
| 109 |
+
## 安全說明
|
| 110 |
+
- 所有 `/api/*`(除 login、health)都需要 token;token 用 `APP_SECRET` 簽名,**改密碼即可讓所有舊登入失效**。
|
| 111 |
+
- 同一 IP 連續 5 次密碼錯誤鎖 10 分鐘。
|
| 112 |
+
- `run_python` / `run_shell` 在獨立子程序中執行,**拿不到環境變數裡的 key**,有記憶體 / CPU / 時間限制;但仍能上網和讀容器檔案,只適合自用。不需要可設 `ENABLE_PYTHON_TOOL=false` / `ENABLE_SHELL_TOOL=false`。
|
| 113 |
+
- 技能和 MCP 伺服器等同你信任的程式碼,只裝來源可靠的。
|
| 114 |
+
- `fetch_url` 會拒絕內網位址。
|
| 115 |
+
|
| 116 |
+
## 本地測試
|
| 117 |
+
```bash
|
| 118 |
+
cp .env.example .env # 填好
|
| 119 |
+
docker build -t my-agent .
|
| 120 |
+
docker run --env-file .env -p 7860:7860 my-agent
|
| 121 |
+
```
|
| 122 |
+
|
| 123 |
+
## 擴充工具
|
| 124 |
+
在 `app/tools.py` 寫一個 async 函數,再加進 `TOOLS` 字典(附 JSON schema)即可,agent 會自動使用。
|
| 125 |
+
|
| 126 |
+
## 檔案結構
|
| 127 |
+
```
|
| 128 |
+
Dockerfile
|
| 129 |
+
requirements.txt
|
| 130 |
+
app/
|
| 131 |
+
main.py # FastAPI 路由、SSE
|
| 132 |
+
agent.py # agent 循環(串流 + 工具調用)
|
| 133 |
+
tools.py # 內建工具 + 分派到 MCP
|
| 134 |
+
providers.py # 模型提供商
|
| 135 |
+
workspace.py # 專案資料夾 ↔ Turso 同步
|
| 136 |
+
mcp_client.py # MCP 連線管理
|
| 137 |
+
skills.py # 技能安裝 / 載入
|
| 138 |
+
db.py # Turso HTTP 客戶端 + 資料存取
|
| 139 |
+
auth.py # 密碼登入 / token
|
| 140 |
+
config.py # 環境變數
|
| 141 |
+
static/index.html # 前端
|
| 142 |
+
```
|
app/agent.py
CHANGED
|
@@ -1,4 +1,5 @@
|
|
| 1 |
"""Agent 主循環:串流呼叫 LLM → 若有工具調用就執行 → 把結果餵回去 → 直到給出最終回答。"""
|
|
|
|
| 2 |
import json
|
| 3 |
from datetime import datetime
|
| 4 |
from zoneinfo import ZoneInfo
|
|
@@ -136,32 +137,37 @@ async def run_agent(conv_id: str, user_text: str, model: str | None = None):
|
|
| 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(
|
| 140 |
for step in range(config.MAX_AGENT_STEPS):
|
| 141 |
last_step = step == config.MAX_AGENT_STEPS - 1
|
| 142 |
content, calls = "", {}
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
slot["function"]["name"]
|
| 163 |
-
|
| 164 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 165 |
|
| 166 |
tool_calls = [calls[k] for k in sorted(calls)]
|
| 167 |
for n, tc in enumerate(tool_calls):
|
|
@@ -175,12 +181,19 @@ async def run_agent(conv_id: str, user_text: str, model: str | None = None):
|
|
| 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 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
"""Agent 主循環:串流呼叫 LLM → 若有工具調用就執行 → 把結果餵回去 → 直到給出最終回答。"""
|
| 2 |
+
import asyncio
|
| 3 |
import json
|
| 4 |
from datetime import datetime
|
| 5 |
from zoneinfo import ZoneInfo
|
|
|
|
| 137 |
messages = [{"role": "system", "content": await build_system_prompt(project)}] + rows_to_messages(history)
|
| 138 |
tools = _clean_schema(tool_schemas())
|
| 139 |
|
| 140 |
+
async with httpx.AsyncClient(timeout=httpx.Timeout(config.LLM_TIMEOUT, connect=config.LLM_CONNECT_TIMEOUT, write=120, pool=60)) as client:
|
| 141 |
for step in range(config.MAX_AGENT_STEPS):
|
| 142 |
last_step = step == config.MAX_AGENT_STEPS - 1
|
| 143 |
content, calls = "", {}
|
| 144 |
+
try:
|
| 145 |
+
async for chunk in stream_completion(client, provider, model_id, messages, tools,
|
| 146 |
+
"none" if last_step else None):
|
| 147 |
+
choices = chunk.get("choices") or []
|
| 148 |
+
if not choices:
|
| 149 |
+
continue
|
| 150 |
+
delta = choices[0].get("delta") or {}
|
| 151 |
+
reasoning = delta.get("reasoning_content") or delta.get("reasoning")
|
| 152 |
+
if reasoning:
|
| 153 |
+
yield {"type": "reasoning", "text": reasoning}
|
| 154 |
+
if delta.get("content"):
|
| 155 |
+
content += delta["content"]
|
| 156 |
+
yield {"type": "token", "text": delta["content"]}
|
| 157 |
+
for tc in delta.get("tool_calls") or []:
|
| 158 |
+
slot = calls.setdefault(tc.get("index", 0), {
|
| 159 |
+
"id": "", "type": "function", "function": {"name": "", "arguments": ""}})
|
| 160 |
+
if tc.get("id"):
|
| 161 |
+
slot["id"] = tc["id"]
|
| 162 |
+
fn = tc.get("function") or {}
|
| 163 |
+
if fn.get("name") and not slot["function"]["name"]:
|
| 164 |
+
slot["function"]["name"] = fn["name"]
|
| 165 |
+
if fn.get("arguments"):
|
| 166 |
+
slot["function"]["arguments"] += fn["arguments"]
|
| 167 |
+
except (asyncio.CancelledError, GeneratorExit):
|
| 168 |
+
if content: # 被停止:保留已經生成的部分
|
| 169 |
+
await asyncio.shield(store.add_message(conv_id, "assistant", content + "\n\n(已停止)"))
|
| 170 |
+
raise
|
| 171 |
|
| 172 |
tool_calls = [calls[k] for k in sorted(calls)]
|
| 173 |
for n, tc in enumerate(tool_calls):
|
|
|
|
| 181 |
await store.add_message(conv_id, "assistant", content,
|
| 182 |
tool_calls=json.dumps(tool_calls, ensure_ascii=False))
|
| 183 |
messages.append({"role": "assistant", "content": content or None, "tool_calls": tool_calls})
|
| 184 |
+
saved: set[str] = set()
|
| 185 |
+
try:
|
| 186 |
+
for tc in tool_calls:
|
| 187 |
+
name, args = tc["function"]["name"], tc["function"]["arguments"]
|
| 188 |
+
yield {"type": "tool_start", "id": tc["id"], "name": name, "arguments": args}
|
| 189 |
+
result = await execute_tool(name, args)
|
| 190 |
+
await store.add_message(conv_id, "tool", result, tool_call_id=tc["id"], name=name)
|
| 191 |
+
saved.add(tc["id"])
|
| 192 |
+
messages.append({"role": "tool", "tool_call_id": tc["id"], "content": result})
|
| 193 |
+
yield {"type": "tool_result", "id": tc["id"], "name": name, "result": result[:4000]}
|
| 194 |
+
except (asyncio.CancelledError, GeneratorExit): # 被停止:補上工具結果,讓對話歷史保持合法
|
| 195 |
+
await asyncio.shield(store.add_messages_tool_stopped(
|
| 196 |
+
conv_id, [tc for tc in tool_calls if tc["id"] not in saved]))
|
| 197 |
+
raise
|
| 198 |
+
|
| 199 |
+
yield {"type": "error", "message": f"已跑了 {config.MAX_AGENT_STEPS} 輪工具調用,暫停一下。按「繼續執行」接著做(上限可用 MAX_AGENT_STEPS 調整)"}
|
app/config.py
CHANGED
|
@@ -16,7 +16,7 @@ TURSO_AUTH_TOKEN = os.getenv("TURSO_AUTH_TOKEN", "")
|
|
| 16 |
|
| 17 |
# 選填
|
| 18 |
TAVILY_API_KEY = os.getenv("TAVILY_API_KEY", "") # 有就用 Tavily 搜尋,沒有就用 ddgs
|
| 19 |
-
MAX_AGENT_STEPS = int(os.getenv("MAX_AGENT_STEPS", "
|
| 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")) # 帶入上下文的歷史訊息數
|
|
@@ -35,6 +35,8 @@ _DEV_SKILLS = ",".join(
|
|
| 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"))
|
|
|
|
| 16 |
|
| 17 |
# 選填
|
| 18 |
TAVILY_API_KEY = os.getenv("TAVILY_API_KEY", "") # 有就用 Tavily 搜尋,沒有就用 ddgs
|
| 19 |
+
MAX_AGENT_STEPS = int(os.getenv("MAX_AGENT_STEPS", "40")) # 單次執行最多幾輪工具調用,到了可按「繼續執行」
|
| 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")) # 帶入上下文的歷史訊息數
|
|
|
|
| 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 |
+
LLM_TIMEOUT = int(os.getenv("LLM_TIMEOUT", "900")) # 等模型回應(兩段輸出之間)最多幾秒;慢模型/長思考可再調高
|
| 39 |
+
LLM_CONNECT_TIMEOUT = int(os.getenv("LLM_CONNECT_TIMEOUT", "60"))
|
| 40 |
PROJECT_MAX_FILE_MB = int(os.getenv("PROJECT_MAX_FILE_MB", "5")) # 單檔超過就不存進資料庫
|
| 41 |
PROJECT_MAX_TOTAL_MB = int(os.getenv("PROJECT_MAX_TOTAL_MB", "100")) # 每個專案存進資料庫的上限
|
| 42 |
MCP_CONNECT_TIMEOUT = int(os.getenv("MCP_CONNECT_TIMEOUT", "60"))
|
app/db.py
CHANGED
|
@@ -168,6 +168,20 @@ async def add_message(cid, role, content, tool_calls=None, tool_call_id=None, na
|
|
| 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 "
|
|
|
|
| 168 |
])
|
| 169 |
|
| 170 |
|
| 171 |
+
async def add_messages_tool_stopped(cid, calls):
|
| 172 |
+
if not calls:
|
| 173 |
+
return
|
| 174 |
+
t = now_ms()
|
| 175 |
+
await db.batch([("INSERT INTO messages (conversation_id, role, content, tool_calls, tool_call_id, name, created_at) "
|
| 176 |
+
"VALUES (?,?,?,?,?,?,?)", [cid, "tool", '{"error": "使用者已停止"}', None, tc["id"],
|
| 177 |
+
tc["function"]["name"], t]) for tc in calls])
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
async def count_messages(cid: str) -> int:
|
| 181 |
+
rows = (await db.execute("SELECT COUNT(*) AS n FROM messages WHERE conversation_id = ?", [cid]))["rows"]
|
| 182 |
+
return int(rows[0]["n"]) if rows else 0
|
| 183 |
+
|
| 184 |
+
|
| 185 |
async def get_messages(cid: str):
|
| 186 |
return (await db.execute(
|
| 187 |
"SELECT id, role, content, tool_calls, tool_call_id, name, created_at FROM messages "
|
app/main.py
CHANGED
|
@@ -11,6 +11,7 @@ from pydantic import BaseModel
|
|
| 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
|
|
@@ -36,6 +37,7 @@ async def lifespan(app: FastAPI):
|
|
| 36 |
log.exception("技能同步失敗")
|
| 37 |
await mcp.reload()
|
| 38 |
yield
|
|
|
|
| 39 |
await mcp.stop_all()
|
| 40 |
await store.db.close()
|
| 41 |
|
|
@@ -49,10 +51,11 @@ class LoginIn(BaseModel):
|
|
| 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):
|
|
@@ -88,6 +91,9 @@ class ModelsQueryIn(BaseModel):
|
|
| 88 |
id: str | None = None
|
| 89 |
|
| 90 |
|
|
|
|
|
|
|
|
|
|
| 91 |
class ProjectIn(BaseModel):
|
| 92 |
name: str | None = None
|
| 93 |
instructions: str | None = None
|
|
@@ -108,6 +114,14 @@ 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}
|
|
@@ -133,7 +147,10 @@ async def me():
|
|
| 133 |
# ---------- 對話 ----------
|
| 134 |
@app.get("/api/conversations", dependencies=AUTH)
|
| 135 |
async def conversations(project: str = "all"):
|
| 136 |
-
|
|
|
|
|
|
|
|
|
|
| 137 |
|
| 138 |
|
| 139 |
@app.get("/api/conversations/{cid}/messages", dependencies=AUTH)
|
|
@@ -154,6 +171,7 @@ async def rename(cid: str, body: RenameIn):
|
|
| 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 |
|
|
@@ -164,11 +182,13 @@ def sse(obj) -> str:
|
|
| 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)
|
|
@@ -177,19 +197,47 @@ async def chat(body: ChatIn):
|
|
| 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 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 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():
|
|
@@ -272,10 +320,48 @@ async def delete_skill(name: str):
|
|
| 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)
|
|
@@ -286,6 +372,7 @@ async def put_mcp(body: MCPConfigIn):
|
|
| 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()}
|
|
|
|
| 11 |
from . import auth, config
|
| 12 |
from . import db as store
|
| 13 |
from . import providers
|
| 14 |
+
from . import runs
|
| 15 |
from . import skills as skillmod
|
| 16 |
from . import workspace
|
| 17 |
from .agent import run_agent
|
|
|
|
| 37 |
log.exception("技能同步失敗")
|
| 38 |
await mcp.reload()
|
| 39 |
yield
|
| 40 |
+
await runs.stop_all()
|
| 41 |
await mcp.stop_all()
|
| 42 |
await store.db.close()
|
| 43 |
|
|
|
|
| 51 |
|
| 52 |
|
| 53 |
class ChatIn(BaseModel):
|
| 54 |
+
message: str = ""
|
| 55 |
conversation_id: str | None = None
|
| 56 |
model: str | None = None # 提供商id::模型id,可隨時切換
|
| 57 |
project_id: str | None = None # 新對話歸屬的專案
|
| 58 |
+
resume: bool = False # 「繼續執行」:不用打字,讓 agent 從中斷處接著做
|
| 59 |
|
| 60 |
|
| 61 |
class RenameIn(BaseModel):
|
|
|
|
| 91 |
id: str | None = None
|
| 92 |
|
| 93 |
|
| 94 |
+
CONTINUE_TEXT = "繼續(從中斷的地方接著完成剛才的任務,不要重做已完成的部分)"
|
| 95 |
+
|
| 96 |
+
|
| 97 |
class ProjectIn(BaseModel):
|
| 98 |
name: str | None = None
|
| 99 |
instructions: str | None = None
|
|
|
|
| 114 |
return FileResponse(STATIC / "index.html", headers={"Cache-Control": "no-cache"})
|
| 115 |
|
| 116 |
|
| 117 |
+
@app.get("/static/{name}")
|
| 118 |
+
async def static_file(name: str):
|
| 119 |
+
if name not in ("marked.min.js", "purify.min.js"):
|
| 120 |
+
raise HTTPException(404)
|
| 121 |
+
return FileResponse(STATIC / name, media_type="application/javascript",
|
| 122 |
+
headers={"Cache-Control": "public, max-age=604800"})
|
| 123 |
+
|
| 124 |
+
|
| 125 |
@app.get("/api/health")
|
| 126 |
async def health():
|
| 127 |
return {"ok": True}
|
|
|
|
| 147 |
# ---------- 對話 ----------
|
| 148 |
@app.get("/api/conversations", dependencies=AUTH)
|
| 149 |
async def conversations(project: str = "all"):
|
| 150 |
+
rows = await store.list_conversations(project)
|
| 151 |
+
for r in rows:
|
| 152 |
+
r["running"] = runs.active(r["id"]) is not None
|
| 153 |
+
return rows
|
| 154 |
|
| 155 |
|
| 156 |
@app.get("/api/conversations/{cid}/messages", dependencies=AUTH)
|
|
|
|
| 171 |
|
| 172 |
@app.delete("/api/conversations/{cid}", dependencies=AUTH)
|
| 173 |
async def delete(cid: str):
|
| 174 |
+
runs.stop(cid)
|
| 175 |
await store.delete_conversation(cid)
|
| 176 |
return {"ok": True}
|
| 177 |
|
|
|
|
| 182 |
|
| 183 |
@app.post("/api/chat", dependencies=AUTH)
|
| 184 |
async def chat(body: ChatIn):
|
| 185 |
+
text = CONTINUE_TEXT if body.resume else body.message.strip()
|
| 186 |
if not text:
|
| 187 |
raise HTTPException(400, "訊息是空的")
|
| 188 |
cid = body.conversation_id
|
| 189 |
conv = await store.get_conversation(cid) if cid else None
|
| 190 |
+
if not conv and body.resume:
|
| 191 |
+
raise HTTPException(400, "沒有可以繼續的對話")
|
| 192 |
if not conv:
|
| 193 |
pid = body.project_id if body.project_id and await store.get_project(body.project_id) else None
|
| 194 |
cid = await store.create_conversation(text.replace("\n", " ")[:40], pid)
|
|
|
|
| 197 |
if body.model and body.model != conv.get("model"):
|
| 198 |
await store.set_conversation_model(cid, body.model)
|
| 199 |
|
| 200 |
+
if runs.active(cid):
|
| 201 |
+
raise HTTPException(409, "這個對話還在執行中,先等它完成或按停止")
|
| 202 |
+
base = await store.count_messages(cid)
|
| 203 |
+
run = runs.start(cid, text, base, lambda: run_agent(cid, text, model))
|
| 204 |
+
return _follow(run, 0, first={"type": "conversation", "id": cid})
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def _follow(run, start: int, first: dict | None = None):
|
| 208 |
async def gen():
|
| 209 |
+
if first:
|
| 210 |
+
yield sse(first)
|
| 211 |
+
async for ev in run.follow(start):
|
| 212 |
+
yield ": ping\n\n" if ev is None else sse(ev)
|
|
|
|
|
|
|
|
|
|
| 213 |
|
| 214 |
+
# 瀏覽器斷線只會結束這個串流,背景的 agent 繼續跑
|
| 215 |
return StreamingResponse(gen(), media_type="text/event-stream",
|
| 216 |
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"})
|
| 217 |
|
| 218 |
|
| 219 |
+
@app.get("/api/conversations/{cid}/run", dependencies=AUTH)
|
| 220 |
+
async def run_info(cid: str):
|
| 221 |
+
r = runs.runs.get(cid)
|
| 222 |
+
if not r:
|
| 223 |
+
return {"running": False}
|
| 224 |
+
return {"running": not r.done, "base_count": r.base_count, "user_text": r.user_text,
|
| 225 |
+
"events": len(r.events), "started": r.started}
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
@app.get("/api/conversations/{cid}/stream", dependencies=AUTH)
|
| 229 |
+
async def run_stream(cid: str, start: int = 0):
|
| 230 |
+
r = runs.runs.get(cid)
|
| 231 |
+
if not r:
|
| 232 |
+
raise HTTPException(404, "沒有進行中的執行")
|
| 233 |
+
return _follow(r, start)
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
@app.post("/api/conversations/{cid}/stop", dependencies=AUTH)
|
| 237 |
+
async def stop_run(cid: str):
|
| 238 |
+
return {"stopped": runs.stop(cid)}
|
| 239 |
+
|
| 240 |
+
|
| 241 |
# ---------- 設定 ----------
|
| 242 |
@app.get("/api/settings", dependencies=AUTH)
|
| 243 |
async def get_settings():
|
|
|
|
| 320 |
|
| 321 |
|
| 322 |
# ---------- MCP ----------
|
| 323 |
+
MASK = "••••"
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
def _mask(v: str) -> str:
|
| 327 |
+
v = str(v)
|
| 328 |
+
if "${" in v or not v:
|
| 329 |
+
return v
|
| 330 |
+
pre = "Bearer " if v.lower().startswith("bearer ") else ""
|
| 331 |
+
return pre + MASK + v[len(pre):][-4:]
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
def _mask_cfg(cfg: dict) -> dict:
|
| 335 |
+
out = {"mcpServers": {}}
|
| 336 |
+
for name, c in (cfg.get("mcpServers") or {}).items():
|
| 337 |
+
c = dict(c)
|
| 338 |
+
for k in ("headers", "env"):
|
| 339 |
+
if isinstance(c.get(k), dict):
|
| 340 |
+
c[k] = {hk: _mask(hv) for hk, hv in c[k].items()}
|
| 341 |
+
out["mcpServers"][name] = c
|
| 342 |
+
return out
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
def _unmask_cfg(new: dict, old: dict) -> dict:
|
| 346 |
+
"""前端送回遮罩過的值時,換回資料庫裡的原值(伺服器改名用 _from 對應)。"""
|
| 347 |
+
olds = old.get("mcpServers") or {}
|
| 348 |
+
for name, c in (new.get("mcpServers") or {}).items():
|
| 349 |
+
src = olds.get(c.pop("_from", None) or name) or {}
|
| 350 |
+
for k in ("headers", "env"):
|
| 351 |
+
if isinstance(c.get(k), dict):
|
| 352 |
+
for hk, hv in list(c[k].items()):
|
| 353 |
+
if MASK in str(hv):
|
| 354 |
+
orig = (src.get(k) or {}).get(hk)
|
| 355 |
+
if orig is None:
|
| 356 |
+
raise HTTPException(400, f"{name} 的 {hk} 需要重新填寫")
|
| 357 |
+
c[k][hk] = orig
|
| 358 |
+
return new
|
| 359 |
+
|
| 360 |
+
|
| 361 |
@app.get("/api/mcp", dependencies=AUTH)
|
| 362 |
async def get_mcp():
|
| 363 |
cfg = await mcp.get_config()
|
| 364 |
+
return {"config": json.dumps(_mask_cfg(cfg), ensure_ascii=False, indent=2), "status": mcp.status()}
|
| 365 |
|
| 366 |
|
| 367 |
@app.put("/api/mcp", dependencies=AUTH)
|
|
|
|
| 372 |
except Exception: # noqa: BLE001
|
| 373 |
raise HTTPException(400, '格式錯誤,需要 {"mcpServers": {...}}')
|
| 374 |
cfg.setdefault("mcpServers", {})
|
| 375 |
+
cfg = _unmask_cfg(cfg, await mcp.get_config())
|
| 376 |
await store.set_setting("mcp_config", json.dumps(cfg, ensure_ascii=False))
|
| 377 |
await mcp.reload()
|
| 378 |
return {"status": mcp.status()}
|
app/runs.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""背景執行:agent 在伺服器上跑,和瀏覽器連線脫鉤。
|
| 2 |
+
|
| 3 |
+
關掉頁面、斷網、重新整理都不會中斷;重新打開對話時從頭重播這次執行的事件並接著看。
|
| 4 |
+
只有按「停止」(POST /api/conversations/{id}/stop)才會中止。
|
| 5 |
+
"""
|
| 6 |
+
import asyncio
|
| 7 |
+
import logging
|
| 8 |
+
import time
|
| 9 |
+
|
| 10 |
+
log = logging.getLogger("runs")
|
| 11 |
+
KEEP_FINISHED = 600 # 結束後保留事件 10 分鐘,讓晚回來的頁面也能看到結尾
|
| 12 |
+
PING_EVERY = 15 # 串流保活,避免代理斷開閒置連線
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class Run:
|
| 16 |
+
def __init__(self, cid: str, user_text: str, base_count: int):
|
| 17 |
+
self.cid, self.user_text, self.base_count = cid, user_text, base_count
|
| 18 |
+
self.events: list[dict] = []
|
| 19 |
+
self.done = False
|
| 20 |
+
self.started = time.time()
|
| 21 |
+
self.cond = asyncio.Condition()
|
| 22 |
+
self.task: asyncio.Task | None = None
|
| 23 |
+
|
| 24 |
+
async def push(self, ev: dict):
|
| 25 |
+
async with self.cond:
|
| 26 |
+
self.events.append(ev)
|
| 27 |
+
self.cond.notify_all()
|
| 28 |
+
|
| 29 |
+
async def finish(self):
|
| 30 |
+
async with self.cond:
|
| 31 |
+
self.done = True
|
| 32 |
+
self.cond.notify_all()
|
| 33 |
+
|
| 34 |
+
async def follow(self, start: int = 0):
|
| 35 |
+
"""逐一 yield 事件;沒有新事件時每 PING_EVERY 秒 yield None 當保活。"""
|
| 36 |
+
i = max(0, start)
|
| 37 |
+
while True:
|
| 38 |
+
async with self.cond:
|
| 39 |
+
if i >= len(self.events) and not self.done:
|
| 40 |
+
try:
|
| 41 |
+
await asyncio.wait_for(self.cond.wait(), PING_EVERY)
|
| 42 |
+
except asyncio.TimeoutError:
|
| 43 |
+
pass
|
| 44 |
+
batch, finished = self.events[i:], self.done
|
| 45 |
+
if not batch and not finished:
|
| 46 |
+
yield None
|
| 47 |
+
continue
|
| 48 |
+
for ev in batch:
|
| 49 |
+
yield ev
|
| 50 |
+
i += len(batch)
|
| 51 |
+
if finished and i >= len(self.events):
|
| 52 |
+
return
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
runs: dict[str, Run] = {}
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def active(cid: str) -> Run | None:
|
| 59 |
+
r = runs.get(cid)
|
| 60 |
+
return r if r and not r.done else None
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def start(cid: str, user_text: str, base_count: int, agen_factory) -> Run:
|
| 64 |
+
run = Run(cid, user_text, base_count)
|
| 65 |
+
runs[cid] = run
|
| 66 |
+
|
| 67 |
+
async def main():
|
| 68 |
+
agen = agen_factory()
|
| 69 |
+
try:
|
| 70 |
+
async for ev in agen:
|
| 71 |
+
await run.push(ev)
|
| 72 |
+
except asyncio.CancelledError:
|
| 73 |
+
try:
|
| 74 |
+
await agen.aclose() # 讓 agent 有機會把已生成的內容存起來
|
| 75 |
+
except Exception: # noqa: BLE001
|
| 76 |
+
pass
|
| 77 |
+
await run.push({"type": "stopped"})
|
| 78 |
+
except Exception as e: # noqa: BLE001
|
| 79 |
+
log.exception("agent error")
|
| 80 |
+
await run.push({"type": "error", "message": f"{type(e).__name__}: {e}"})
|
| 81 |
+
finally:
|
| 82 |
+
await run.finish()
|
| 83 |
+
asyncio.get_running_loop().call_later(
|
| 84 |
+
KEEP_FINISHED, lambda: runs.pop(cid, None) if runs.get(cid) is run else None)
|
| 85 |
+
|
| 86 |
+
run.task = asyncio.create_task(main())
|
| 87 |
+
return run
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def stop(cid: str) -> bool:
|
| 91 |
+
r = active(cid)
|
| 92 |
+
if r and r.task:
|
| 93 |
+
r.task.cancel()
|
| 94 |
+
return True
|
| 95 |
+
return False
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
async def stop_all():
|
| 99 |
+
for r in list(runs.values()):
|
| 100 |
+
if r.task and not r.done:
|
| 101 |
+
r.task.cancel()
|
app/static/index.html
CHANGED
|
The diff for this file is too large to render.
See raw diff
|
|
|
app/static/marked.min.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* marked v12.0.2 - a markdown parser
|
| 3 |
+
* Copyright (c) 2011-2024, Christopher Jeffrey. (MIT Licensed)
|
| 4 |
+
* https://github.com/markedjs/marked
|
| 5 |
+
*/
|
| 6 |
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).marked={})}(this,(function(e){"use strict";function t(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}function n(t){e.defaults=t}e.defaults={async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null};const s=/[&<>"']/,r=new RegExp(s.source,"g"),i=/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,l=new RegExp(i.source,"g"),o={"&":"&","<":"<",">":">",'"':""","'":"'"},a=e=>o[e];function c(e,t){if(t){if(s.test(e))return e.replace(r,a)}else if(i.test(e))return e.replace(l,a);return e}const h=/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/gi;function p(e){return e.replace(h,((e,t)=>"colon"===(t=t.toLowerCase())?":":"#"===t.charAt(0)?"x"===t.charAt(1)?String.fromCharCode(parseInt(t.substring(2),16)):String.fromCharCode(+t.substring(1)):""))}const u=/(^|[^\[])\^/g;function k(e,t){let n="string"==typeof e?e:e.source;t=t||"";const s={replace:(e,t)=>{let r="string"==typeof t?t:t.source;return r=r.replace(u,"$1"),n=n.replace(e,r),s},getRegex:()=>new RegExp(n,t)};return s}function g(e){try{e=encodeURI(e).replace(/%25/g,"%")}catch(e){return null}return e}const f={exec:()=>null};function d(e,t){const n=e.replace(/\|/g,((e,t,n)=>{let s=!1,r=t;for(;--r>=0&&"\\"===n[r];)s=!s;return s?"|":" |"})).split(/ \|/);let s=0;if(n[0].trim()||n.shift(),n.length>0&&!n[n.length-1].trim()&&n.pop(),t)if(n.length>t)n.splice(t);else for(;n.length<t;)n.push("");for(;s<n.length;s++)n[s]=n[s].trim().replace(/\\\|/g,"|");return n}function x(e,t,n){const s=e.length;if(0===s)return"";let r=0;for(;r<s;){const i=e.charAt(s-r-1);if(i!==t||n){if(i===t||!n)break;r++}else r++}return e.slice(0,s-r)}function b(e,t,n,s){const r=t.href,i=t.title?c(t.title):null,l=e[1].replace(/\\([\[\]])/g,"$1");if("!"!==e[0].charAt(0)){s.state.inLink=!0;const e={type:"link",raw:n,href:r,title:i,text:l,tokens:s.inlineTokens(l)};return s.state.inLink=!1,e}return{type:"image",raw:n,href:r,title:i,text:c(l)}}class w{options;rules;lexer;constructor(t){this.options=t||e.defaults}space(e){const t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){const t=this.rules.block.code.exec(e);if(t){const e=t[0].replace(/^ {1,4}/gm,"");return{type:"code",raw:t[0],codeBlockStyle:"indented",text:this.options.pedantic?e:x(e,"\n")}}}fences(e){const t=this.rules.block.fences.exec(e);if(t){const e=t[0],n=function(e,t){const n=e.match(/^(\s+)(?:```)/);if(null===n)return t;const s=n[1];return t.split("\n").map((e=>{const t=e.match(/^\s+/);if(null===t)return e;const[n]=t;return n.length>=s.length?e.slice(s.length):e})).join("\n")}(e,t[3]||"");return{type:"code",raw:e,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:n}}}heading(e){const t=this.rules.block.heading.exec(e);if(t){let e=t[2].trim();if(/#$/.test(e)){const t=x(e,"#");this.options.pedantic?e=t.trim():t&&!/ $/.test(t)||(e=t.trim())}return{type:"heading",raw:t[0],depth:t[1].length,text:e,tokens:this.lexer.inline(e)}}}hr(e){const t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:t[0]}}blockquote(e){const t=this.rules.block.blockquote.exec(e);if(t){let e=t[0].replace(/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,"\n $1");e=x(e.replace(/^ *>[ \t]?/gm,""),"\n");const n=this.lexer.state.top;this.lexer.state.top=!0;const s=this.lexer.blockTokens(e);return this.lexer.state.top=n,{type:"blockquote",raw:t[0],tokens:s,text:e}}}list(e){let t=this.rules.block.list.exec(e);if(t){let n=t[1].trim();const s=n.length>1,r={type:"list",raw:"",ordered:s,start:s?+n.slice(0,-1):"",loose:!1,items:[]};n=s?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=s?n:"[*+-]");const i=new RegExp(`^( {0,3}${n})((?:[\t ][^\\n]*)?(?:\\n|$))`);let l="",o="",a=!1;for(;e;){let n=!1;if(!(t=i.exec(e)))break;if(this.rules.block.hr.test(e))break;l=t[0],e=e.substring(l.length);let s=t[2].split("\n",1)[0].replace(/^\t+/,(e=>" ".repeat(3*e.length))),c=e.split("\n",1)[0],h=0;this.options.pedantic?(h=2,o=s.trimStart()):(h=t[2].search(/[^ ]/),h=h>4?1:h,o=s.slice(h),h+=t[1].length);let p=!1;if(!s&&/^ *$/.test(c)&&(l+=c+"\n",e=e.substring(c.length+1),n=!0),!n){const t=new RegExp(`^ {0,${Math.min(3,h-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ \t][^\\n]*)?(?:\\n|$))`),n=new RegExp(`^ {0,${Math.min(3,h-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),r=new RegExp(`^ {0,${Math.min(3,h-1)}}(?:\`\`\`|~~~)`),i=new RegExp(`^ {0,${Math.min(3,h-1)}}#`);for(;e;){const a=e.split("\n",1)[0];if(c=a,this.options.pedantic&&(c=c.replace(/^ {1,4}(?=( {4})*[^ ])/g," ")),r.test(c))break;if(i.test(c))break;if(t.test(c))break;if(n.test(e))break;if(c.search(/[^ ]/)>=h||!c.trim())o+="\n"+c.slice(h);else{if(p)break;if(s.search(/[^ ]/)>=4)break;if(r.test(s))break;if(i.test(s))break;if(n.test(s))break;o+="\n"+c}p||c.trim()||(p=!0),l+=a+"\n",e=e.substring(a.length+1),s=c.slice(h)}}r.loose||(a?r.loose=!0:/\n *\n *$/.test(l)&&(a=!0));let u,k=null;this.options.gfm&&(k=/^\[[ xX]\] /.exec(o),k&&(u="[ ] "!==k[0],o=o.replace(/^\[[ xX]\] +/,""))),r.items.push({type:"list_item",raw:l,task:!!k,checked:u,loose:!1,text:o,tokens:[]}),r.raw+=l}r.items[r.items.length-1].raw=l.trimEnd(),r.items[r.items.length-1].text=o.trimEnd(),r.raw=r.raw.trimEnd();for(let e=0;e<r.items.length;e++)if(this.lexer.state.top=!1,r.items[e].tokens=this.lexer.blockTokens(r.items[e].text,[]),!r.loose){const t=r.items[e].tokens.filter((e=>"space"===e.type)),n=t.length>0&&t.some((e=>/\n.*\n/.test(e.raw)));r.loose=n}if(r.loose)for(let e=0;e<r.items.length;e++)r.items[e].loose=!0;return r}}html(e){const t=this.rules.block.html.exec(e);if(t){return{type:"html",block:!0,raw:t[0],pre:"pre"===t[1]||"script"===t[1]||"style"===t[1],text:t[0]}}}def(e){const t=this.rules.block.def.exec(e);if(t){const e=t[1].toLowerCase().replace(/\s+/g," "),n=t[2]?t[2].replace(/^<(.*)>$/,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",s=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:e,raw:t[0],href:n,title:s}}}table(e){const t=this.rules.block.table.exec(e);if(!t)return;if(!/[:|]/.test(t[2]))return;const n=d(t[1]),s=t[2].replace(/^\||\| *$/g,"").split("|"),r=t[3]&&t[3].trim()?t[3].replace(/\n[ \t]*$/,"").split("\n"):[],i={type:"table",raw:t[0],header:[],align:[],rows:[]};if(n.length===s.length){for(const e of s)/^ *-+: *$/.test(e)?i.align.push("right"):/^ *:-+: *$/.test(e)?i.align.push("center"):/^ *:-+ *$/.test(e)?i.align.push("left"):i.align.push(null);for(const e of n)i.header.push({text:e,tokens:this.lexer.inline(e)});for(const e of r)i.rows.push(d(e,i.header.length).map((e=>({text:e,tokens:this.lexer.inline(e)}))));return i}}lheading(e){const t=this.rules.block.lheading.exec(e);if(t)return{type:"heading",raw:t[0],depth:"="===t[2].charAt(0)?1:2,text:t[1],tokens:this.lexer.inline(t[1])}}paragraph(e){const t=this.rules.block.paragraph.exec(e);if(t){const e="\n"===t[1].charAt(t[1].length-1)?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:e,tokens:this.lexer.inline(e)}}}text(e){const t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){const t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:c(t[1])}}tag(e){const t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&/^<a /i.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&/^<\/a>/i.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&/^<(pre|code|kbd|script)(\s|>)/i.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&/^<\/(pre|code|kbd|script)(\s|>)/i.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){const t=this.rules.inline.link.exec(e);if(t){const e=t[2].trim();if(!this.options.pedantic&&/^</.test(e)){if(!/>$/.test(e))return;const t=x(e.slice(0,-1),"\\");if((e.length-t.length)%2==0)return}else{const e=function(e,t){if(-1===e.indexOf(t[1]))return-1;let n=0;for(let s=0;s<e.length;s++)if("\\"===e[s])s++;else if(e[s]===t[0])n++;else if(e[s]===t[1]&&(n--,n<0))return s;return-1}(t[2],"()");if(e>-1){const n=(0===t[0].indexOf("!")?5:4)+t[1].length+e;t[2]=t[2].substring(0,e),t[0]=t[0].substring(0,n).trim(),t[3]=""}}let n=t[2],s="";if(this.options.pedantic){const e=/^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(n);e&&(n=e[1],s=e[3])}else s=t[3]?t[3].slice(1,-1):"";return n=n.trim(),/^</.test(n)&&(n=this.options.pedantic&&!/>$/.test(e)?n.slice(1):n.slice(1,-1)),b(t,{href:n?n.replace(this.rules.inline.anyPunctuation,"$1"):n,title:s?s.replace(this.rules.inline.anyPunctuation,"$1"):s},t[0],this.lexer)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){const e=t[(n[2]||n[1]).replace(/\s+/g," ").toLowerCase()];if(!e){const e=n[0].charAt(0);return{type:"text",raw:e,text:e}}return b(n,e,n[0],this.lexer)}}emStrong(e,t,n=""){let s=this.rules.inline.emStrongLDelim.exec(e);if(!s)return;if(s[3]&&n.match(/[\p{L}\p{N}]/u))return;if(!(s[1]||s[2]||"")||!n||this.rules.inline.punctuation.exec(n)){const n=[...s[0]].length-1;let r,i,l=n,o=0;const a="*"===s[0][0]?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(a.lastIndex=0,t=t.slice(-1*e.length+n);null!=(s=a.exec(t));){if(r=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!r)continue;if(i=[...r].length,s[3]||s[4]){l+=i;continue}if((s[5]||s[6])&&n%3&&!((n+i)%3)){o+=i;continue}if(l-=i,l>0)continue;i=Math.min(i,i+l+o);const t=[...s[0]][0].length,a=e.slice(0,n+s.index+t+i);if(Math.min(n,i)%2){const e=a.slice(1,-1);return{type:"em",raw:a,text:e,tokens:this.lexer.inlineTokens(e)}}const c=a.slice(2,-2);return{type:"strong",raw:a,text:c,tokens:this.lexer.inlineTokens(c)}}}}codespan(e){const t=this.rules.inline.code.exec(e);if(t){let e=t[2].replace(/\n/g," ");const n=/[^ ]/.test(e),s=/^ /.test(e)&&/ $/.test(e);return n&&s&&(e=e.substring(1,e.length-1)),e=c(e,!0),{type:"codespan",raw:t[0],text:e}}}br(e){const t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e){const t=this.rules.inline.del.exec(e);if(t)return{type:"del",raw:t[0],text:t[2],tokens:this.lexer.inlineTokens(t[2])}}autolink(e){const t=this.rules.inline.autolink.exec(e);if(t){let e,n;return"@"===t[2]?(e=c(t[1]),n="mailto:"+e):(e=c(t[1]),n=e),{type:"link",raw:t[0],text:e,href:n,tokens:[{type:"text",raw:e,text:e}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let e,n;if("@"===t[2])e=c(t[0]),n="mailto:"+e;else{let s;do{s=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??""}while(s!==t[0]);e=c(t[0]),n="www."===t[1]?"http://"+t[0]:t[0]}return{type:"link",raw:t[0],text:e,href:n,tokens:[{type:"text",raw:e,text:e}]}}}inlineText(e){const t=this.rules.inline.text.exec(e);if(t){let e;return e=this.lexer.state.inRawBlock?t[0]:c(t[0]),{type:"text",raw:t[0],text:e}}}}const m=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,y=/(?:[*+-]|\d{1,9}[.)])/,$=k(/^(?!bull |blockCode|fences|blockquote|heading|html)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html))+?)\n {0,3}(=+|-+) *(?:\n+|$)/).replace(/bull/g,y).replace(/blockCode/g,/ {4}/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).getRegex(),z=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,T=/(?!\s*\])(?:\\.|[^\[\]\\])+/,R=k(/^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/).replace("label",T).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),_=k(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,y).getRegex(),A="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",S=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,I=k("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n *)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$))","i").replace("comment",S).replace("tag",A).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),E=k(z).replace("hr",m).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",A).getRegex(),q={blockquote:k(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",E).getRegex(),code:/^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/,def:R,fences:/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,heading:/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,hr:m,html:I,lheading:$,list:_,newline:/^(?: *(?:\n|$))+/,paragraph:E,table:f,text:/^[^\n]+/},Z=k("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",m).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code"," {4}[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",A).getRegex(),L={...q,table:Z,paragraph:k(z).replace("hr",m).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Z).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",A).getRegex()},P={...q,html:k("^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:\"[^\"]*\"|'[^']*'|\\s[^'\"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))").replace("comment",S).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:f,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:k(z).replace("hr",m).replace("heading"," *#{1,6} *[^\n]").replace("lheading",$).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Q=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,v=/^( {2,}|\\)\n(?!\s*$)/,B="\\p{P}\\p{S}",C=k(/^((?![*_])[\spunctuation])/,"u").replace(/punctuation/g,B).getRegex(),M=k(/^(?:\*+(?:((?!\*)[punct])|[^\s*]))|^_+(?:((?!_)[punct])|([^\s_]))/,"u").replace(/punct/g,B).getRegex(),O=k("^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)[punct](\\*+)(?=[\\s]|$)|[^punct\\s](\\*+)(?!\\*)(?=[punct\\s]|$)|(?!\\*)[punct\\s](\\*+)(?=[^punct\\s])|[\\s](\\*+)(?!\\*)(?=[punct])|(?!\\*)[punct](\\*+)(?!\\*)(?=[punct])|[^punct\\s](\\*+)(?=[^punct\\s])","gu").replace(/punct/g,B).getRegex(),D=k("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)[punct](_+)(?=[\\s]|$)|[^punct\\s](_+)(?!_)(?=[punct\\s]|$)|(?!_)[punct\\s](_+)(?=[^punct\\s])|[\\s](_+)(?!_)(?=[punct])|(?!_)[punct](_+)(?!_)(?=[punct])","gu").replace(/punct/g,B).getRegex(),j=k(/\\([punct])/,"gu").replace(/punct/g,B).getRegex(),H=k(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),U=k(S).replace("(?:--\x3e|$)","--\x3e").getRegex(),X=k("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",U).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),F=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,N=k(/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/).replace("label",F).replace("href",/<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),G=k(/^!?\[(label)\]\[(ref)\]/).replace("label",F).replace("ref",T).getRegex(),J=k(/^!?\[(ref)\](?:\[\])?/).replace("ref",T).getRegex(),K={_backpedal:f,anyPunctuation:j,autolink:H,blockSkip:/\[[^[\]]*?\]\([^\(\)]*?\)|`[^`]*?`|<[^<>]*?>/g,br:v,code:/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,del:f,emStrongLDelim:M,emStrongRDelimAst:O,emStrongRDelimUnd:D,escape:Q,link:N,nolink:J,punctuation:C,reflink:G,reflinkSearch:k("reflink|nolink(?!\\()","g").replace("reflink",G).replace("nolink",J).getRegex(),tag:X,text:/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,url:f},V={...K,link:k(/^!?\[(label)\]\((.*?)\)/).replace("label",F).getRegex(),reflink:k(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",F).getRegex()},W={...K,escape:k(Q).replace("])","~|])").getRegex(),url:k(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,"i").replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/},Y={...W,br:k(v).replace("{2,}","*").getRegex(),text:k(W.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},ee={normal:q,gfm:L,pedantic:P},te={normal:K,gfm:W,breaks:Y,pedantic:V};class ne{tokens;options;state;tokenizer;inlineQueue;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||e.defaults,this.options.tokenizer=this.options.tokenizer||new w,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};const n={block:ee.normal,inline:te.normal};this.options.pedantic?(n.block=ee.pedantic,n.inline=te.pedantic):this.options.gfm&&(n.block=ee.gfm,this.options.breaks?n.inline=te.breaks:n.inline=te.gfm),this.tokenizer.rules=n}static get rules(){return{block:ee,inline:te}}static lex(e,t){return new ne(t).lex(e)}static lexInline(e,t){return new ne(t).inlineTokens(e)}lex(e){e=e.replace(/\r\n|\r/g,"\n"),this.blockTokens(e,this.tokens);for(let e=0;e<this.inlineQueue.length;e++){const t=this.inlineQueue[e];this.inlineTokens(t.src,t.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,t=[]){let n,s,r,i;for(e=this.options.pedantic?e.replace(/\t/g," ").replace(/^ +$/gm,""):e.replace(/^( *)(\t+)/gm,((e,t,n)=>t+" ".repeat(n.length)));e;)if(!(this.options.extensions&&this.options.extensions.block&&this.options.extensions.block.some((s=>!!(n=s.call({lexer:this},e,t))&&(e=e.substring(n.raw.length),t.push(n),!0)))))if(n=this.tokenizer.space(e))e=e.substring(n.raw.length),1===n.raw.length&&t.length>0?t[t.length-1].raw+="\n":t.push(n);else if(n=this.tokenizer.code(e))e=e.substring(n.raw.length),s=t[t.length-1],!s||"paragraph"!==s.type&&"text"!==s.type?t.push(n):(s.raw+="\n"+n.raw,s.text+="\n"+n.text,this.inlineQueue[this.inlineQueue.length-1].src=s.text);else if(n=this.tokenizer.fences(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.heading(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.hr(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.blockquote(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.list(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.html(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.def(e))e=e.substring(n.raw.length),s=t[t.length-1],!s||"paragraph"!==s.type&&"text"!==s.type?this.tokens.links[n.tag]||(this.tokens.links[n.tag]={href:n.href,title:n.title}):(s.raw+="\n"+n.raw,s.text+="\n"+n.raw,this.inlineQueue[this.inlineQueue.length-1].src=s.text);else if(n=this.tokenizer.table(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.lheading(e))e=e.substring(n.raw.length),t.push(n);else{if(r=e,this.options.extensions&&this.options.extensions.startBlock){let t=1/0;const n=e.slice(1);let s;this.options.extensions.startBlock.forEach((e=>{s=e.call({lexer:this},n),"number"==typeof s&&s>=0&&(t=Math.min(t,s))})),t<1/0&&t>=0&&(r=e.substring(0,t+1))}if(this.state.top&&(n=this.tokenizer.paragraph(r)))s=t[t.length-1],i&&"paragraph"===s.type?(s.raw+="\n"+n.raw,s.text+="\n"+n.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=s.text):t.push(n),i=r.length!==e.length,e=e.substring(n.raw.length);else if(n=this.tokenizer.text(e))e=e.substring(n.raw.length),s=t[t.length-1],s&&"text"===s.type?(s.raw+="\n"+n.raw,s.text+="\n"+n.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=s.text):t.push(n);else if(e){const t="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(t);break}throw new Error(t)}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){let n,s,r,i,l,o,a=e;if(this.tokens.links){const e=Object.keys(this.tokens.links);if(e.length>0)for(;null!=(i=this.tokenizer.rules.inline.reflinkSearch.exec(a));)e.includes(i[0].slice(i[0].lastIndexOf("[")+1,-1))&&(a=a.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+a.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;null!=(i=this.tokenizer.rules.inline.blockSkip.exec(a));)a=a.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+a.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);for(;null!=(i=this.tokenizer.rules.inline.anyPunctuation.exec(a));)a=a.slice(0,i.index)+"++"+a.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);for(;e;)if(l||(o=""),l=!1,!(this.options.extensions&&this.options.extensions.inline&&this.options.extensions.inline.some((s=>!!(n=s.call({lexer:this},e,t))&&(e=e.substring(n.raw.length),t.push(n),!0)))))if(n=this.tokenizer.escape(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.tag(e))e=e.substring(n.raw.length),s=t[t.length-1],s&&"text"===n.type&&"text"===s.type?(s.raw+=n.raw,s.text+=n.text):t.push(n);else if(n=this.tokenizer.link(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.reflink(e,this.tokens.links))e=e.substring(n.raw.length),s=t[t.length-1],s&&"text"===n.type&&"text"===s.type?(s.raw+=n.raw,s.text+=n.text):t.push(n);else if(n=this.tokenizer.emStrong(e,a,o))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.codespan(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.br(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.del(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.autolink(e))e=e.substring(n.raw.length),t.push(n);else if(this.state.inLink||!(n=this.tokenizer.url(e))){if(r=e,this.options.extensions&&this.options.extensions.startInline){let t=1/0;const n=e.slice(1);let s;this.options.extensions.startInline.forEach((e=>{s=e.call({lexer:this},n),"number"==typeof s&&s>=0&&(t=Math.min(t,s))})),t<1/0&&t>=0&&(r=e.substring(0,t+1))}if(n=this.tokenizer.inlineText(r))e=e.substring(n.raw.length),"_"!==n.raw.slice(-1)&&(o=n.raw.slice(-1)),l=!0,s=t[t.length-1],s&&"text"===s.type?(s.raw+=n.raw,s.text+=n.text):t.push(n);else if(e){const t="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(t);break}throw new Error(t)}}else e=e.substring(n.raw.length),t.push(n);return t}}class se{options;constructor(t){this.options=t||e.defaults}code(e,t,n){const s=(t||"").match(/^\S*/)?.[0];return e=e.replace(/\n$/,"")+"\n",s?'<pre><code class="language-'+c(s)+'">'+(n?e:c(e,!0))+"</code></pre>\n":"<pre><code>"+(n?e:c(e,!0))+"</code></pre>\n"}blockquote(e){return`<blockquote>\n${e}</blockquote>\n`}html(e,t){return e}heading(e,t,n){return`<h${t}>${e}</h${t}>\n`}hr(){return"<hr>\n"}list(e,t,n){const s=t?"ol":"ul";return"<"+s+(t&&1!==n?' start="'+n+'"':"")+">\n"+e+"</"+s+">\n"}listitem(e,t,n){return`<li>${e}</li>\n`}checkbox(e){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox">'}paragraph(e){return`<p>${e}</p>\n`}table(e,t){return t&&(t=`<tbody>${t}</tbody>`),"<table>\n<thead>\n"+e+"</thead>\n"+t+"</table>\n"}tablerow(e){return`<tr>\n${e}</tr>\n`}tablecell(e,t){const n=t.header?"th":"td";return(t.align?`<${n} align="${t.align}">`:`<${n}>`)+e+`</${n}>\n`}strong(e){return`<strong>${e}</strong>`}em(e){return`<em>${e}</em>`}codespan(e){return`<code>${e}</code>`}br(){return"<br>"}del(e){return`<del>${e}</del>`}link(e,t,n){const s=g(e);if(null===s)return n;let r='<a href="'+(e=s)+'"';return t&&(r+=' title="'+t+'"'),r+=">"+n+"</a>",r}image(e,t,n){const s=g(e);if(null===s)return n;let r=`<img src="${e=s}" alt="${n}"`;return t&&(r+=` title="${t}"`),r+=">",r}text(e){return e}}class re{strong(e){return e}em(e){return e}codespan(e){return e}del(e){return e}html(e){return e}text(e){return e}link(e,t,n){return""+n}image(e,t,n){return""+n}br(){return""}}class ie{options;renderer;textRenderer;constructor(t){this.options=t||e.defaults,this.options.renderer=this.options.renderer||new se,this.renderer=this.options.renderer,this.renderer.options=this.options,this.textRenderer=new re}static parse(e,t){return new ie(t).parse(e)}static parseInline(e,t){return new ie(t).parseInline(e)}parse(e,t=!0){let n="";for(let s=0;s<e.length;s++){const r=e[s];if(this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[r.type]){const e=r,t=this.options.extensions.renderers[e.type].call({parser:this},e);if(!1!==t||!["space","hr","heading","code","table","blockquote","list","html","paragraph","text"].includes(e.type)){n+=t||"";continue}}switch(r.type){case"space":continue;case"hr":n+=this.renderer.hr();continue;case"heading":{const e=r;n+=this.renderer.heading(this.parseInline(e.tokens),e.depth,p(this.parseInline(e.tokens,this.textRenderer)));continue}case"code":{const e=r;n+=this.renderer.code(e.text,e.lang,!!e.escaped);continue}case"table":{const e=r;let t="",s="";for(let t=0;t<e.header.length;t++)s+=this.renderer.tablecell(this.parseInline(e.header[t].tokens),{header:!0,align:e.align[t]});t+=this.renderer.tablerow(s);let i="";for(let t=0;t<e.rows.length;t++){const n=e.rows[t];s="";for(let t=0;t<n.length;t++)s+=this.renderer.tablecell(this.parseInline(n[t].tokens),{header:!1,align:e.align[t]});i+=this.renderer.tablerow(s)}n+=this.renderer.table(t,i);continue}case"blockquote":{const e=r,t=this.parse(e.tokens);n+=this.renderer.blockquote(t);continue}case"list":{const e=r,t=e.ordered,s=e.start,i=e.loose;let l="";for(let t=0;t<e.items.length;t++){const n=e.items[t],s=n.checked,r=n.task;let o="";if(n.task){const e=this.renderer.checkbox(!!s);i?n.tokens.length>0&&"paragraph"===n.tokens[0].type?(n.tokens[0].text=e+" "+n.tokens[0].text,n.tokens[0].tokens&&n.tokens[0].tokens.length>0&&"text"===n.tokens[0].tokens[0].type&&(n.tokens[0].tokens[0].text=e+" "+n.tokens[0].tokens[0].text)):n.tokens.unshift({type:"text",text:e+" "}):o+=e+" "}o+=this.parse(n.tokens,i),l+=this.renderer.listitem(o,r,!!s)}n+=this.renderer.list(l,t,s);continue}case"html":{const e=r;n+=this.renderer.html(e.text,e.block);continue}case"paragraph":{const e=r;n+=this.renderer.paragraph(this.parseInline(e.tokens));continue}case"text":{let i=r,l=i.tokens?this.parseInline(i.tokens):i.text;for(;s+1<e.length&&"text"===e[s+1].type;)i=e[++s],l+="\n"+(i.tokens?this.parseInline(i.tokens):i.text);n+=t?this.renderer.paragraph(l):l;continue}default:{const e='Token with "'+r.type+'" type was not found.';if(this.options.silent)return console.error(e),"";throw new Error(e)}}}return n}parseInline(e,t){t=t||this.renderer;let n="";for(let s=0;s<e.length;s++){const r=e[s];if(this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[r.type]){const e=this.options.extensions.renderers[r.type].call({parser:this},r);if(!1!==e||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(r.type)){n+=e||"";continue}}switch(r.type){case"escape":{const e=r;n+=t.text(e.text);break}case"html":{const e=r;n+=t.html(e.text);break}case"link":{const e=r;n+=t.link(e.href,e.title,this.parseInline(e.tokens,t));break}case"image":{const e=r;n+=t.image(e.href,e.title,e.text);break}case"strong":{const e=r;n+=t.strong(this.parseInline(e.tokens,t));break}case"em":{const e=r;n+=t.em(this.parseInline(e.tokens,t));break}case"codespan":{const e=r;n+=t.codespan(e.text);break}case"br":n+=t.br();break;case"del":{const e=r;n+=t.del(this.parseInline(e.tokens,t));break}case"text":{const e=r;n+=t.text(e.text);break}default:{const e='Token with "'+r.type+'" type was not found.';if(this.options.silent)return console.error(e),"";throw new Error(e)}}}return n}}class le{options;constructor(t){this.options=t||e.defaults}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}}class oe{defaults={async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null};options=this.setOptions;parse=this.#e(ne.lex,ie.parse);parseInline=this.#e(ne.lexInline,ie.parseInline);Parser=ie;Renderer=se;TextRenderer=re;Lexer=ne;Tokenizer=w;Hooks=le;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(const s of e)switch(n=n.concat(t.call(this,s)),s.type){case"table":{const e=s;for(const s of e.header)n=n.concat(this.walkTokens(s.tokens,t));for(const s of e.rows)for(const e of s)n=n.concat(this.walkTokens(e.tokens,t));break}case"list":{const e=s;n=n.concat(this.walkTokens(e.items,t));break}default:{const e=s;this.defaults.extensions?.childTokens?.[e.type]?this.defaults.extensions.childTokens[e.type].forEach((s=>{const r=e[s].flat(1/0);n=n.concat(this.walkTokens(r,t))})):e.tokens&&(n=n.concat(this.walkTokens(e.tokens,t)))}}return n}use(...e){const t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach((e=>{const n={...e};if(n.async=this.defaults.async||n.async||!1,e.extensions&&(e.extensions.forEach((e=>{if(!e.name)throw new Error("extension name required");if("renderer"in e){const n=t.renderers[e.name];t.renderers[e.name]=n?function(...t){let s=e.renderer.apply(this,t);return!1===s&&(s=n.apply(this,t)),s}:e.renderer}if("tokenizer"in e){if(!e.level||"block"!==e.level&&"inline"!==e.level)throw new Error("extension level must be 'block' or 'inline'");const n=t[e.level];n?n.unshift(e.tokenizer):t[e.level]=[e.tokenizer],e.start&&("block"===e.level?t.startBlock?t.startBlock.push(e.start):t.startBlock=[e.start]:"inline"===e.level&&(t.startInline?t.startInline.push(e.start):t.startInline=[e.start]))}"childTokens"in e&&e.childTokens&&(t.childTokens[e.name]=e.childTokens)})),n.extensions=t),e.renderer){const t=this.defaults.renderer||new se(this.defaults);for(const n in e.renderer){if(!(n in t))throw new Error(`renderer '${n}' does not exist`);if("options"===n)continue;const s=n,r=e.renderer[s],i=t[s];t[s]=(...e)=>{let n=r.apply(t,e);return!1===n&&(n=i.apply(t,e)),n||""}}n.renderer=t}if(e.tokenizer){const t=this.defaults.tokenizer||new w(this.defaults);for(const n in e.tokenizer){if(!(n in t))throw new Error(`tokenizer '${n}' does not exist`);if(["options","rules","lexer"].includes(n))continue;const s=n,r=e.tokenizer[s],i=t[s];t[s]=(...e)=>{let n=r.apply(t,e);return!1===n&&(n=i.apply(t,e)),n}}n.tokenizer=t}if(e.hooks){const t=this.defaults.hooks||new le;for(const n in e.hooks){if(!(n in t))throw new Error(`hook '${n}' does not exist`);if("options"===n)continue;const s=n,r=e.hooks[s],i=t[s];le.passThroughHooks.has(n)?t[s]=e=>{if(this.defaults.async)return Promise.resolve(r.call(t,e)).then((e=>i.call(t,e)));const n=r.call(t,e);return i.call(t,n)}:t[s]=(...e)=>{let n=r.apply(t,e);return!1===n&&(n=i.apply(t,e)),n}}n.hooks=t}if(e.walkTokens){const t=this.defaults.walkTokens,s=e.walkTokens;n.walkTokens=function(e){let n=[];return n.push(s.call(this,e)),t&&(n=n.concat(t.call(this,e))),n}}this.defaults={...this.defaults,...n}})),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return ne.lex(e,t??this.defaults)}parser(e,t){return ie.parse(e,t??this.defaults)}#e(e,t){return(n,s)=>{const r={...s},i={...this.defaults,...r};!0===this.defaults.async&&!1===r.async&&(i.silent||console.warn("marked(): The async option was set to true by an extension. The async: false option sent to parse will be ignored."),i.async=!0);const l=this.#t(!!i.silent,!!i.async);if(null==n)return l(new Error("marked(): input parameter is undefined or null"));if("string"!=typeof n)return l(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(n)+", string expected"));if(i.hooks&&(i.hooks.options=i),i.async)return Promise.resolve(i.hooks?i.hooks.preprocess(n):n).then((t=>e(t,i))).then((e=>i.hooks?i.hooks.processAllTokens(e):e)).then((e=>i.walkTokens?Promise.all(this.walkTokens(e,i.walkTokens)).then((()=>e)):e)).then((e=>t(e,i))).then((e=>i.hooks?i.hooks.postprocess(e):e)).catch(l);try{i.hooks&&(n=i.hooks.preprocess(n));let s=e(n,i);i.hooks&&(s=i.hooks.processAllTokens(s)),i.walkTokens&&this.walkTokens(s,i.walkTokens);let r=t(s,i);return i.hooks&&(r=i.hooks.postprocess(r)),r}catch(e){return l(e)}}}#t(e,t){return n=>{if(n.message+="\nPlease report this to https://github.com/markedjs/marked.",e){const e="<p>An error occurred:</p><pre>"+c(n.message+"",!0)+"</pre>";return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}}const ae=new oe;function ce(e,t){return ae.parse(e,t)}ce.options=ce.setOptions=function(e){return ae.setOptions(e),ce.defaults=ae.defaults,n(ce.defaults),ce},ce.getDefaults=t,ce.defaults=e.defaults,ce.use=function(...e){return ae.use(...e),ce.defaults=ae.defaults,n(ce.defaults),ce},ce.walkTokens=function(e,t){return ae.walkTokens(e,t)},ce.parseInline=ae.parseInline,ce.Parser=ie,ce.parser=ie.parse,ce.Renderer=se,ce.TextRenderer=re,ce.Lexer=ne,ce.lexer=ne.lex,ce.Tokenizer=w,ce.Hooks=le,ce.parse=ce;const he=ce.options,pe=ce.setOptions,ue=ce.use,ke=ce.walkTokens,ge=ce.parseInline,fe=ce,de=ie.parse,xe=ne.lex;e.Hooks=le,e.Lexer=ne,e.Marked=oe,e.Parser=ie,e.Renderer=se,e.TextRenderer=re,e.Tokenizer=w,e.getDefaults=t,e.lexer=xe,e.marked=ce,e.options=he,e.parse=fe,e.parseInline=ge,e.parser=de,e.setOptions=pe,e.use=ue,e.walkTokens=ke}));
|
app/static/purify.min.js
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/*! @license DOMPurify 3.5.0 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.5.0/LICENSE */
|
| 2 |
+
(function(e,t){typeof exports==`object`&&typeof module<`u`?module.exports=t():typeof define==`function`&&define.amd?define([],t):(e=typeof globalThis<`u`?globalThis:e||self,e.DOMPurify=t())})(this,function(){"use strict";function e(e,t){this.v=e,this.k=t}function t(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function n(e){if(Array.isArray(e))return e}function r(e,t){var n=e==null?null:typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n!=null){var r,i,a,o,s=[],c=!0,l=!1;try{if(a=(n=n.call(e)).next,t===0){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){l=!0,i=e}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(l)throw i}}return s}}function i(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
|
| 3 |
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}
|
| 4 |
+
/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */
|
| 5 |
+
function a(e,t){return n(e)||r(e,t)||o(e,t)||i()}function o(e,n){if(e){if(typeof e==`string`)return t(e,n);var r={}.toString.call(e).slice(8,-1);return r===`Object`&&e.constructor&&(r=e.constructor.name),r===`Map`||r===`Set`?Array.from(e):r===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?t(e,n):void 0}}function s(t){var n,r;function i(n,r){try{var o=t[n](r),s=o.value,c=s instanceof e;Promise.resolve(c?s.v:s).then(function(e){if(c){var r=n===`return`&&s.k?n:`next`;if(!s.k||e.done)return i(r,e);e=t[r](e).value}a(!!o.done,e)},function(e){i(`throw`,e)})}catch(e){a(2,e)}}function a(e,t){e===2?n.reject(t):n.resolve({value:t,done:e}),(n=n.next)?i(n.key,n.arg):r=null}this._invoke=function(e,t){return new Promise(function(a,o){var s={key:e,arg:t,resolve:a,reject:o,next:null};r?r=r.next=s:(n=r=s,i(e,t))})},typeof t.return!=`function`&&(this.return=void 0)}s.prototype[typeof Symbol==`function`&&Symbol.asyncIterator||`@@asyncIterator`]=function(){return this},s.prototype.next=function(e){return this._invoke(`next`,e)},s.prototype.throw=function(e){return this._invoke(`throw`,e)},s.prototype.return=function(e){return this._invoke(`return`,e)};let c=Object.entries,l=Object.keys,u=Object.setPrototypeOf,d=Object.isFrozen,f=Object.getPrototypeOf,p=Object.getOwnPropertyDescriptor,m=Object.freeze,h=Object.seal,g=Object.create,ee=typeof Reflect<`u`&&Reflect,te=ee.apply,ne=ee.construct;m||(m=function(e){return e}),h||(h=function(e){return e}),te||(te=function(e,t){var n=[...arguments].slice(2);return e.apply(t,n)}),ne||(ne=function(e){return new e(...[...arguments].slice(1))});let _=E(Array.prototype.forEach),re=E(Array.prototype.lastIndexOf),ie=E(Array.prototype.pop),ae=E(Array.prototype.push),oe=E(Array.prototype.slice),se=E(Array.prototype.splice),ce=Array.isArray,le=Ce(Set),ue=E(Set.prototype.add),de=E(Set.prototype.has),fe=E(Set.prototype.delete),pe=Ce(Map),me=E(Map.prototype.get),he=E(Map.prototype.set),v=E(String.prototype.toLowerCase),ge=E(String.prototype.toString),_e=E(String.prototype.match),ve=E(String.prototype.replace),ye=E(String.prototype.indexOf),be=E(String.prototype.trim),xe=E(Number.prototype.toString),y=E(Boolean.prototype.toString),b=typeof BigInt>`u`?null:E(BigInt.prototype.toString),Se=typeof Symbol>`u`?null:E(Symbol.prototype.toString),x=E(Object.prototype.hasOwnProperty),S=E(Object.prototype.toString),C=RegExp.prototype.test,w=function(e,t){return e instanceof RegExp&&(e.lastIndex=0),te(C,e,[t])},T=Ce(TypeError);function E(e){return function(t){var n=[...arguments].slice(1);return te(e,t,n)}}function Ce(e){return function(){return ne(e,[...arguments])}}function D(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:v;if(u&&u(e,null),!ce(t))return e;let r=t.length;for(;r--;){let i=t[r];if(typeof i==`string`){let e=n(i);e!==i&&(d(t)||(t[r]=e),i=e)}e[i]=!0}return e}function O(e){for(let t=0;t<e.length;t++)x(e,t)||(e[t]=null);return e}function we(e){let t=g(null);for(let r of c(e)){var n=a(r,2);let i=n[0],o=n[1];x(e,i)&&(t[i]=ce(o)?O(o):o&&typeof o==`object`&&o.constructor===Object?we(o):o)}return t}function Te(e){let t=g(null),n=l(e),r=n.length;for(;r--;)t[n[r]]=e[n[r]];return t}function Ee(e){switch(typeof e){case`string`:return e;case`number`:return xe(e);case`boolean`:return y(e);case`bigint`:return b?b(e):`0`;case`symbol`:return Se?Se(e):`Symbol()`;case`undefined`:return S(e);case`function`:case`object`:{if(e===null)return S(e);let t=e,n=k(t,`toString`);if(typeof n==`function`){let e=n(t);return typeof e==`string`?e:S(e)}return S(e)}default:return S(e)}}function k(e,t){for(;e!==null;){let n=p(e,t);if(n){if(n.get)return E(n.get);if(typeof n.value==`function`)return E(n.value)}e=f(e)}function n(){return null}return n}function De(e,t){for(;e!==null;){let n=p(e,t);if(n)return n.get?E(n.get):null;e=f(e)}return null}function Oe(e){if(!e)return!1;try{return w(e,``),!0}catch(e){return!1}}let ke=m(/* @__PURE__ */ `a.abbr.acronym.address.area.article.aside.audio.b.bdi.bdo.big.blink.blockquote.body.br.button.canvas.caption.center.cite.code.col.colgroup.content.data.datalist.dd.decorator.del.details.dfn.dialog.dir.div.dl.dt.element.em.fieldset.figcaption.figure.font.footer.form.h1.h2.h3.h4.h5.h6.head.header.hgroup.hr.html.i.img.input.ins.kbd.label.legend.li.main.map.mark.marquee.menu.menuitem.meter.nav.nobr.ol.optgroup.option.output.p.picture.pre.progress.q.rp.rt.ruby.s.samp.search.section.select.shadow.slot.small.source.spacer.span.strike.strong.style.sub.summary.sup.table.tbody.td.template.textarea.tfoot.th.thead.time.tr.track.tt.u.ul.var.video.wbr`.split(`.`)),Ae=m(/* @__PURE__ */ `svg.a.altglyph.altglyphdef.altglyphitem.animatecolor.animatemotion.animatetransform.circle.clippath.defs.desc.ellipse.filter.font.g.glyph.glyphref.hkern.image.line.lineargradient.marker.mask.metadata.mpath.path.pattern.polygon.polyline.radialgradient.rect.stop.style.switch.symbol.text.textpath.title.tref.tspan.view.vkern`.split(`.`)),je=m([`feBlend`,`feColorMatrix`,`feComponentTransfer`,`feComposite`,`feConvolveMatrix`,`feDiffuseLighting`,`feDisplacementMap`,`feDistantLight`,`feDropShadow`,`feFlood`,`feFuncA`,`feFuncB`,`feFuncG`,`feFuncR`,`feGaussianBlur`,`feImage`,`feMerge`,`feMergeNode`,`feMorphology`,`feOffset`,`fePointLight`,`feSpecularLighting`,`feSpotLight`,`feTile`,`feTurbulence`]),Me=m([`animate`,`color-profile`,`cursor`,`discard`,`font-face`,`font-face-format`,`font-face-name`,`font-face-src`,`font-face-uri`,`foreignobject`,`hatch`,`hatchpath`,`mesh`,`meshgradient`,`meshpatch`,`meshrow`,`missing-glyph`,`script`,`set`,`solidcolor`,`unknown`,`use`]),Ne=m(/* @__PURE__ */ `math.menclose.merror.mfenced.mfrac.mglyph.mi.mlabeledtr.mmultiscripts.mn.mo.mover.mpadded.mphantom.mroot.mrow.ms.mspace.msqrt.mstyle.msub.msup.msubsup.mtable.mtd.mtext.mtr.munder.munderover.mprescripts`.split(`.`)),Pe=m([`maction`,`maligngroup`,`malignmark`,`mlongdiv`,`mscarries`,`mscarry`,`msgroup`,`mstack`,`msline`,`msrow`,`semantics`,`annotation`,`annotation-xml`,`mprescripts`,`none`]),Fe=m([`#text`]),Ie=m(/* @__PURE__ */ `accept.action.align.alt.autocapitalize.autocomplete.autopictureinpicture.autoplay.background.bgcolor.border.capture.cellpadding.cellspacing.checked.cite.class.clear.color.cols.colspan.command.commandfor.controls.controlslist.coords.crossorigin.datetime.decoding.default.dir.disabled.disablepictureinpicture.disableremoteplayback.download.draggable.enctype.enterkeyhint.exportparts.face.for.headers.height.hidden.high.href.hreflang.id.inert.inputmode.integrity.ismap.kind.label.lang.list.loading.loop.low.max.maxlength.media.method.min.minlength.multiple.muted.name.nonce.noshade.novalidate.nowrap.open.optimum.part.pattern.placeholder.playsinline.popover.popovertarget.popovertargetaction.poster.preload.pubdate.radiogroup.readonly.rel.required.rev.reversed.role.rows.rowspan.spellcheck.scope.selected.shape.size.sizes.slot.span.srclang.start.src.srcset.step.style.summary.tabindex.title.translate.type.usemap.valign.value.width.wrap.xmlns`.split(`.`)),Le=m(/* @__PURE__ */ `accent-height.accumulate.additive.alignment-baseline.amplitude.ascent.attributename.attributetype.azimuth.basefrequency.baseline-shift.begin.bias.by.class.clip.clippathunits.clip-path.clip-rule.color.color-interpolation.color-interpolation-filters.color-profile.color-rendering.cx.cy.d.dx.dy.diffuseconstant.direction.display.divisor.dominant-baseline.dur.edgemode.elevation.end.exponent.fill.fill-opacity.fill-rule.filter.filterunits.flood-color.flood-opacity.font-family.font-size.font-size-adjust.font-stretch.font-style.font-variant.font-weight.fx.fy.g1.g2.glyph-name.glyphref.gradientunits.gradienttransform.height.href.id.image-rendering.in.in2.intercept.k.k1.k2.k3.k4.kerning.keypoints.keysplines.keytimes.lang.lengthadjust.letter-spacing.kernelmatrix.kernelunitlength.lighting-color.local.marker-end.marker-mid.marker-start.markerheight.markerunits.markerwidth.maskcontentunits.maskunits.max.mask.mask-type.media.method.mode.min.name.numoctaves.offset.operator.opacity.order.orient.orientation.origin.overflow.paint-order.path.pathlength.patterncontentunits.patterntransform.patternunits.pointer-events.points.preservealpha.preserveaspectratio.primitiveunits.r.rx.ry.radius.refx.refy.repeatcount.repeatdur.restart.result.rotate.scale.seed.shape-rendering.slope.specularconstant.specularexponent.spreadmethod.startoffset.stddeviation.stitchtiles.stop-color.stop-opacity.stroke-dasharray.stroke-dashoffset.stroke-linecap.stroke-linejoin.stroke-miterlimit.stroke-opacity.stroke.stroke-width.style.surfacescale.systemlanguage.tabindex.tablevalues.targetx.targety.transform.transform-origin.text-anchor.text-decoration.text-orientation.text-rendering.textlength.type.u1.u2.unicode.values.vector-effect.viewbox.visibility.version.vert-adv-y.vert-origin-x.vert-origin-y.width.word-spacing.wrap.writing-mode.xchannelselector.ychannelselector.x.x1.x2.xmlns.y.y1.y2.z.zoomandpan`.split(`.`)),Re=m(/* @__PURE__ */ `accent.accentunder.align.bevelled.close.columnalign.columnlines.columnspacing.columnspan.denomalign.depth.dir.display.displaystyle.encoding.fence.frame.height.href.id.largeop.length.linethickness.lquote.lspace.mathbackground.mathcolor.mathsize.mathvariant.maxsize.minsize.movablelimits.notation.numalign.open.rowalign.rowlines.rowspacing.rowspan.rspace.rquote.scriptlevel.scriptminsize.scriptsizemultiplier.selection.separator.separators.stretchy.subscriptshift.supscriptshift.symmetric.voffset.width.xmlns`.split(`.`)),ze=m([`xlink:href`,`xml:id`,`xlink:title`,`xml:space`,`xmlns:xlink`]),Be=h(/{{[\w\W]*|^[\w\W]*}}/g),Ve=h(/<%[\w\W]*|^[\w\W]*%>/g),He=h(/\${[\w\W]*/g),Ue=h(/{{|}}|\${|<%|%>/),We=h(/[^\t\n\f\r ]/),Ge=h(/\u0000/g),Ke=h(/^data-[\-\w.\u00B7-\uFFFF]+$/),qe=h(/^aria-[\-\w]+$/),Je=h(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Ye=h(/^(?:\w+script|data):/i),Xe=h(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Ze=h(/^html$/i),Qe=h(/^[a-z][.\w]*(-[.\w]+)+$/i),$e=h(/<[/\w!]/g),et=h(/<[/\w]/g),tt=h(/<[/\w]|^-?>|--!?>|<!-$/g),nt=h(/<\/no(script|embed|frames)/i),rt=h(/\/>/i),it=h(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i),at=h(/^[\r\n\t ]+/),A={element:1,text:3,processingInstruction:7,comment:8,document:9,documentFragment:11},ot=m(D({},[`style`,`script`,`xmp`,`iframe`,`noembed`,`noframes`,`plaintext`,`noscript`])),st=m(D({},[`textarea`,`title`])),ct=m(D({},[`area`,`base`,`basefont`,`bgsound`,`br`,`col`,`embed`,`frame`,`hr`,`img`,`input`,`keygen`,`link`,`meta`,`param`,`source`,`track`,`wbr`])),lt=function(){return typeof window>`u`?null:window},ut=function(e,t){if(typeof e!=`object`||typeof e.createPolicy!=`function`)return null;let n=null,r=`data-tt-policy-suffix`;t&&t.hasAttribute(r)&&(n=t.getAttribute(r));let i=`dompurify`+(n?`#`+n:``);try{return e.createPolicy(i,{createHTML(e){return e},createScriptURL(e){return e}})}catch(e){return console.warn(`TrustedTypes policy `+i+` could not be created.`),null}},dt=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},j=function(e,t,n,r){return x(e,t)&&ce(e[t])?D(r.base?Te(r.base):{},e[t],r.transform):n},ft=function(e,t,n){let r=x(e,t)?e[t]:void 0;return r&&typeof r==`object`?we(r):n};function pt(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:lt(),t=e=>pt(e);if(t.version=`3.5.0`,t.removed=[],!e||!e.document||e.document.nodeType!==A.document||!e.Element)return t.isSupported=!1,t;let n=e.document,r=n,i=r.currentScript,a=e.HTMLTemplateElement,o=e.Node,s=e.Element,l=e.NodeFilter,u=e.DOMParser,d=e.trustedTypes,f=s.prototype,p=k(f,`cloneNode`),ee=k(f,`remove`),te=k(f,`removeChild`),ne=k(f,`removeAttributeNode`),xe=k(f,`nextSibling`),y=k(f,`childNodes`),b=k(f,`parentNode`),Se=k(f,`shadowRoot`),S=k(f,`attributes`),C=o&&o.prototype?k(o.prototype,`nodeType`):null,E=o&&o.prototype?k(o.prototype,`nodeName`):null,Ce=o&&o.prototype?k(o.prototype,`ownerDocument`):null,O=function(e){return C?C(e):e.nodeType},M=function(e){return E?E(e):e.nodeName},mt=De(f,`namespaceURI`),ht=function(e){return mt?mt(e):e.namespaceURI},gt=function(e){return O(e)===A.element?S(e):null};if(typeof a==`function`){let e=n.createElement(`template`);e.content&&e.content.ownerDocument&&(n=e.content.ownerDocument)}let N,P=``,_t,vt=!1,yt=0,bt=function(){if(yt>0)throw T(`A configured TRUSTED_TYPES_POLICY callback (createHTML or createScriptURL) must not call DOMPurify.sanitize, as that causes infinite recursion. Do not pass a policy whose callbacks wrap DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted Types" section of the README.`)},xt=function(e){bt(),yt++;try{return N.createHTML(e)}finally{yt--}},St=function(e){return N&&$t?xt(e):e},Ct=function(e){bt(),yt++;try{return N.createScriptURL(e)}finally{yt--}},wt=function(){return vt||(_t=ut(d,i),vt=!0),_t},Tt=n,Et=Tt.implementation,Dt=Tt.createNodeIterator,Ot=Tt.createDocumentFragment,kt=Tt.getElementsByTagName,At=r.importNode,F=dt();t.isSupported=typeof c==`function`&&typeof b==`function`&&Et&&Et.createHTMLDocument!==void 0;let jt=Be,Mt=Ve,Nt=He,Pt=Ke,Ft=qe,It=Ye,Lt=Xe,Rt=Qe,zt=Je,I=null,Bt=D({},[...ke,...Ae,...je,...Ne,...Fe]),L=null,Vt=D({},[...Ie,...Le,...Re,...ze]),R=null,Ht=null,Ut=null,z=Object.seal(g(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),Wt=!0,Gt=!0,Kt=!1,qt=!0,B=!1,V=!0,H=!1,Jt=!1,Yt=null,Xt=null,Zt=!1,U=!1,Qt=!1,$t=!1,en=!0,tn=!1,nn=`user-content-`,rn=!0,an=!1,W=null,G=null,K=!1,q=null,on=D({},/* @__PURE__ */ `annotation-xml.audio.colgroup.desc.foreignobject.head.iframe.math.mi.mn.mo.ms.mtext.noembed.noframes.noscript.plaintext.script.selectedcontent.style.svg.template.thead.title.video.xmp`.split(`.`)),sn=null,cn=D({},[`audio`,`video`,`img`,`source`,`image`,`track`]),ln=null,un=D({},[`alt`,`class`,`for`,`id`,`label`,`name`,`pattern`,`placeholder`,`role`,`summary`,`title`,`value`,`style`,`xmlns`]),dn=`http://www.w3.org/1998/Math/MathML`,fn=`http://www.w3.org/2000/svg`,J=`http://www.w3.org/1999/xhtml`,Y=J,pn=!1,mn=null,hn=D({},[dn,fn,J],ge),gn=m(D({},[`mi`,`mo`,`mn`,`ms`,`mtext`])),_n=null,vn=m(D({},[`annotation-xml`])),yn=null,bn=m(g(null)),xn=D({},[`title`,`style`,`font`,`a`,`script`]),X=null,Sn=[`application/xhtml+xml`,`text/html`],Z=null,Cn=null,wn=null,Tn=n.createElement(`form`),En=function(e){return e instanceof RegExp||e instanceof Function},Dn=function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};e&&typeof e==`object`||(e={}),e=we(e),X=Sn.indexOf(e.PARSER_MEDIA_TYPE)===-1?`text/html`:e.PARSER_MEDIA_TYPE,Z=X===`application/xhtml+xml`?ge:v,I=j(e,`ALLOWED_TAGS`,Bt,{transform:Z}),L=j(e,`ALLOWED_ATTR`,Vt,{transform:Z}),mn=j(e,`ALLOWED_NAMESPACES`,hn,{transform:ge}),ln=j(e,`ADD_URI_SAFE_ATTR`,un,{transform:Z,base:un}),sn=j(e,`ADD_DATA_URI_TAGS`,cn,{transform:Z,base:cn}),q=j(e,`FORBID_CONTENTS`,on,{transform:Z}),Ht=j(e,`FORBID_TAGS`,g(null),{transform:Z}),Ut=j(e,`FORBID_ATTR`,g(null),{transform:Z}),K=x(e,`USE_PROFILES`)?e.USE_PROFILES&&typeof e.USE_PROFILES==`object`?we(e.USE_PROFILES):e.USE_PROFILES:!1,Wt=e.ALLOW_ARIA_ATTR!==!1,Gt=e.ALLOW_DATA_ATTR!==!1,Kt=e.ALLOW_UNKNOWN_PROTOCOLS||!1,qt=e.ALLOW_SELF_CLOSE_IN_ATTR!==!1,B=e.SAFE_FOR_TEMPLATES||!1,V=e.SAFE_FOR_XML!==!1,H=e.WHOLE_DOCUMENT||!1,U=e.RETURN_DOM||!1,Qt=e.RETURN_DOM_FRAGMENT||!1,$t=e.RETURN_TRUSTED_TYPE||!1,Zt=e.FORCE_BODY||!1,en=e.SANITIZE_DOM!==!1,tn=e.SANITIZE_NAMED_PROPS||!1,rn=e.KEEP_CONTENT!==!1,an=e.IN_PLACE||!1,zt=Oe(e.ALLOWED_URI_REGEXP)?e.ALLOWED_URI_REGEXP:Je,Y=typeof e.NAMESPACE==`string`?e.NAMESPACE:J,_n=ft(e,`MATHML_TEXT_INTEGRATION_POINTS`,gn),yn=ft(e,`HTML_INTEGRATION_POINTS`,vn);let t=ft(e,`CUSTOM_ELEMENT_HANDLING`,bn);if(R=g(null),x(t,`tagNameCheck`)&&En(t.tagNameCheck)&&(R.tagNameCheck=t.tagNameCheck),x(t,`attributeNameCheck`)&&En(t.attributeNameCheck)&&(R.attributeNameCheck=t.attributeNameCheck),x(t,`allowCustomizedBuiltInElements`)&&typeof t.allowCustomizedBuiltInElements==`boolean`&&(R.allowCustomizedBuiltInElements=t.allowCustomizedBuiltInElements),h(R),B&&(Gt=!1),Qt&&(U=!0),K&&((x(e,`ALLOWED_TAGS`)||x(e,`ALLOWED_ATTR`))&&typeof console<`u`&&typeof console.warn==`function`&&console.warn(`DOMPurify: USE_PROFILES overrides ALLOWED_TAGS and ALLOWED_ATTR. Do not use these options together.`),I=D({},Fe),L=g(null),K.html===!0&&(D(I,ke),D(L,Ie)),K.svg===!0&&(D(I,Ae),D(L,Le),D(L,ze)),K.svgFilters===!0&&(D(I,je),D(L,Le),D(L,ze)),K.mathMl===!0&&(D(I,Ne),D(L,Re),D(L,ze))),z.tagCheck=null,z.attributeCheck=null,x(e,`ADD_TAGS`)&&(typeof e.ADD_TAGS==`function`?z.tagCheck=e.ADD_TAGS:ce(e.ADD_TAGS)&&(I===Bt&&(I=Te(I)),D(I,e.ADD_TAGS,Z))),x(e,`ADD_ATTR`)&&(typeof e.ADD_ATTR==`function`?z.attributeCheck=e.ADD_ATTR:ce(e.ADD_ATTR)&&(L===Vt&&(L=Te(L)),D(L,e.ADD_ATTR,Z))),x(e,`ADD_FORBID_CONTENTS`)&&ce(e.ADD_FORBID_CONTENTS)&&(q===on&&(q=Te(q)),D(q,e.ADD_FORBID_CONTENTS,Z)),rn&&(I[`#text`]=!0),H&&D(I,[`html`,`head`,`body`]),I.table&&(I.tbody=!0,delete Ht.tbody),e.TRUSTED_TYPES_POLICY){if(typeof e.TRUSTED_TYPES_POLICY.createHTML!=`function`)throw T(`TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.`);if(typeof e.TRUSTED_TYPES_POLICY.createScriptURL!=`function`)throw T(`TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.`);let t=N;N=e.TRUSTED_TYPES_POLICY;try{P=xt(``)}catch(e){throw N=t,e}}else e.TRUSTED_TYPES_POLICY===null?(N=void 0,P=``):(N===void 0&&(N=wt()),N&&typeof P==`string`&&(P=xt(``)));Cn=m(e)},On=D({},[...Ae,...je,...Me]),kn=D({},[...Ne,...Pe]),An=function(e,t,n){return t===J?e===`svg`:t===dn?e===`svg`&&(n===`annotation-xml`||_n[n]):!!On[e]},jn=function(e,t,n){return t===J?e===`math`:t===fn?e===`math`&&yn[n]:!!kn[e]},Mn=function(e,t,n){return t===fn&&!yn[n]||t===dn&&!_n[n]?!1:!kn[e]&&(xn[e]||!On[e])},Nn=function(e){let t=ht(e),n=v(M(e)),r=b(e),i=Y,a=`template`;return r&&O(r)===A.element&&(i=ht(r),a=v(M(r))),mn[t]?t===fn?An(n,i,a):t===dn?jn(n,i,a):t===J?Mn(n,i,a):X===`application/xhtml+xml`:!1},Q=function(e){ae(t.removed,{element:e}),qn(e);try{b(e).removeChild(e)}catch(t){if(ee(e),!b(e))throw T(`a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place`)}},Pn=function(e,t,n){try{ne(e,t)}catch(t){try{e.removeAttribute(n)}catch(e){}}},Fn=function(e){zn(e);let t=y(e);t&&_(oe(t),t=>{try{te(e,t)}catch(e){}}),O(e)===A.element&&Ln(e,!1)},In=function(e,n,r){if(!r)try{r=n.getAttributeNode(e)}catch(e){r=null}if(ae(t.removed,{attribute:r||null,from:n}),r)Pn(n,r,e);else try{n.removeAttribute(e)}catch(e){}if(e===`is`){if(U||Qt)try{Q(n)}catch(e){}else try{n.setAttribute(e,``)}catch(e){}}},Ln=function(e,t){let n=S(e);if(n)for(let r=n.length-1;r>=0;--r){let i=n[r],a=i&&i.name;typeof a==`string`&&!(t&&L[Z(a)])&&Pn(e,i,a)}},Rn=function(e,t){let n=arguments.length>2&&arguments[2]!==void 0&&arguments[2],r=[e];for(;r.length>0;){let e=r.pop();if(t(e)===!1)continue;if(n&&O(e)===A.element){let t=Se(e);ar(t)&&r.push(t)}let i=y(e);if(i)for(let e=i.length-1;e>=0;--e)r.push(i[e])}},zn=function(e){Rn(e,e=>{O(e)===A.element&&Ln(e,!0)})},Bn=function(e){let t=[];return Rn(e,e=>{t.push(e)},!0),t},Vn=function(e,t){let n=le();_(Bn(e),e=>{O(e)===A.element&&ue(n,e)}),_(t,e=>{O(e)===A.element&&!de(n,e)&&Ln(e,!0)})},Hn=function(e,n){let r=!1;return _(t.removed,t=>{t.element&&(r=r||t.element===e,zn(t.element))}),Vn(e,n),r},Un=function(e,t){Fn(e),Hn(e,t)},Wn=function(e,t){let n=W,r=null,i=()=>(r||(r=le(),_(t,e=>{ue(r,e)})),r);for(let t=0;;t++){let r=Bn(e),a=[e],o=!1;if(_(r,e=>{O(e)===A.documentFragment?ae(a,e):!o&&!de(n,e)&&(o=de(i(),e))}),!o)return;if(t>=8)throw T(`the tree kept changing during in-place sanitization; refusing to return it`);_(a,(t,n)=>{Gn(t,n>0,e,i())})}},Gn=function(e,t,n,r){let i=Zn(e),a;for(;a=i.nextNode();)de(r,a)&&!de(W,a)&&(t&&$(F.uponSanitizeShadowNode,a,null),xr(a,n))},Kn=function(e){if(!W)return;ue(W,e);let t=me(G,e);if(t!==void 0){if(t>=8)throw T(`the tree kept changing during in-place sanitization; refusing to return it`);he(G,e,t+1)}},qn=function(e){W&&(fe(W,e),me(G,e)===void 0&&he(G,e,0))},Jn=function(e,t){return V?e===`patchsrc`||e===`for`&&t!==`label`&&t!==`output`:!1},Yn=function(e){V&&Rn(e,e=>{let t=O(e);if(t===A.processingInstruction||t===A.comment&&w(et,e.data)){try{ee(e)}catch(e){}return!1}if(t===A.element){let t=e,n=Z(M(e));try{t.hasAttribute&&t.hasAttribute(`patchsrc`)&&t.removeAttribute(`patchsrc`),t.hasAttribute&&t.hasAttribute(`for`)&&Jn(`for`,n)&&t.removeAttribute(`for`)}catch(e){}}return!0})},Xn=function(e){let t=null,r=null;if(Zt)e=`<remove></remove>`+e;else{let t=_e(e,at);r=t&&t[0]}X===`application/xhtml+xml`&&Y===J&&(e=`<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>`+e+`</body></html>`);let i=N?xt(e):e;if(Y===J)try{t=new u().parseFromString(i,X)}catch(e){}if(!t||!t.documentElement){t=Et.createDocument(Y,`template`,null);try{t.documentElement.innerHTML=pn?P:i}catch(e){}}let a=t.body||t.documentElement;return e&&r&&a.insertBefore(n.createTextNode(r),a.childNodes[0]||null),Y===J?kt.call(t,H?`html`:`body`)[0]:H?t.documentElement:a},Zn=function(e){let t=arguments.length>1&&arguments[1]!==void 0&&arguments[1],n=Ce?Ce(e):e.ownerDocument;return Dt.call(n||e,e,(t?0:l.SHOW_ELEMENT)|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},Qn=function(e){return e=ve(e,jt,` `),e=ve(e,Mt,` `),e=ve(e,Nt,` `),e},$n=function(e){var t;nr(e);let n=(t=e.querySelectorAll)==null?void 0:t.call(e,`template`);n&&_(n,e=>{ar(e.content)&&$n(e.content)})},er=D({},[`caption`,`colgroup`,`col`,`thead`,`tbody`,`tfoot`,`tr`,`td`,`th`,`style`,`script`,`template`]),tr=function(e){var t;if(X===`application/xhtml+xml`)return;let n=(t=e.querySelectorAll)==null?void 0:t.call(e,`table,tbody,thead,tfoot,tr,colgroup`);n&&n.length!==0&&_(n,t=>{_(oe(y(t)),n=>{let r=O(n);if(!(r===A.text?w(We,n.data):r===A.element&&!er[v(M(n))]))return;let i=t;for(;i&&v(M(i))!==`table`;)i=i===e?null:b(i);let a=i&&i!==e?b(i):null;if(a)try{a.insertBefore(n,i)}catch(e){}})})},nr=function(e){tr(e),e.normalize();let t=Zn(e,!0),n=null,r=t.nextNode();for(;r;){let e=r.data;if(w(Ge,e)&&(e=ve(e,Ge,``),r.data=e),w(Ue,e)&&(e=Qn(e),r.data=e),e&&O(r)===A.text){if(n){let t=n.data,r=t[t.length-1]+e[0];w(Ue,r)&&(n.data=Qn(t+e[0]))}n=r}r=t.nextNode()}},rr=function(e){let t=E?E(e):null;return typeof t!=`string`||Z(t)!==`form`?!1:typeof e.nodeName!=`string`||typeof e.textContent!=`string`||typeof e.removeChild!=`function`||e.attributes!==S(e)||typeof e.removeAttribute!=`function`||typeof e.removeAttributeNode!=`function`||typeof e.getAttributeNode!=`function`||typeof e.setAttribute!=`function`||typeof e.namespaceURI!=`string`||typeof e.insertBefore!=`function`||typeof e.hasChildNodes!=`function`||e.nodeType!==C(e)||e.childNodes!==y(e)},ir=function(e){if(!C||typeof e!=`object`||!e)return null;try{let t=C(e);return typeof t==`number`?t:null}catch(e){return null}},ar=function(e){return ir(e)===A.documentFragment},or=function(e){return ir(e)!==null};function $(e,n,r){e.length!==0&&_(e,e=>{e.call(t,n,r,Cn)})}let sr=function(e,t){let n=!!ct[t],r=!!ot[t];return!n&&!r&&!st[t]||ht(e)!==J?!1:n?e.hasChildNodes():or(e.firstElementChild)?!0:r&&typeof e.textContent==`string`&&w($e,e.textContent)},cr=function(e,t,n){return!!(V&&n===A.element&&e.hasChildNodes()&&!or(e.firstElementChild)&&w($e,e.textContent)&&w($e,e.innerHTML)||V&&n===A.element&&sr(e,t)||n===A.processingInstruction||V&&n===A.comment&&w(tt,e.data))},lr=function(e,t){return e instanceof RegExp?w(e,t):e instanceof Function&&!!e(t,...[...arguments].slice(2))},ur=function(e,t,n){if(!Ht[t]&&gr(t)&&lr(R.tagNameCheck,t))return!1;if(rn&&!q[t]&&!q[v(t)]){let t=b(e),r=y(e);if(r&&t){let i=r.length;for(let a=i-1;a>=0;--a){let i=e===n?p(r[a],!0):r[a];t.insertBefore(i,xe(e))}}}return Q(e),!0},dr=function(e,t,n,r){return e.length===0?t:t===n||t===r?Te(t):t},fr=function(e,t){return e===t||b(e)!==null?!1:(an&&zn(e),qn(e),!0)},pr=function(e,n){if(Kn(e),$(F.beforeSanitizeElements,e,null),fr(e,n))return!0;if(rr(e))return Q(e),!0;let r=Z(M(e)),i=O(e);if(I=dr(F.uponSanitizeElement,I,Bt,Yt),$(F.uponSanitizeElement,e,{tagName:r,allowedTags:I}),fr(e,n))return!0;if(cr(e,r,i))return Q(e),!0;if((Ht[r]||!(z.tagCheck instanceof Function&&z.tagCheck(r))&&!I[r])&&ur(e,r,n))return!0;if(i===A.element&&!Nn(e)||(r===`noscript`||r===`noembed`||r===`noframes`)&&w(nt,e.innerHTML))return Q(e),!0;if(B&&i===A.text){let n=e.textContent,r=Qn(n);n!==r&&(ae(t.removed,{element:e.cloneNode()}),e.textContent=r)}return $(F.afterSanitizeElements,e,null),fr(e,n)},mr=function(e,t,r){if(Ut[t]||Jn(t,e)||en&&(t===`id`||t===`name`)&&(r in n||r in Tn))return!1;let i=L[t]||z.attributeCheck instanceof Function&&z.attributeCheck(t,e);if(Gt&&w(Pt,t)||Wt&&w(Ft,t))return!0;if(!i)return gr(e)&&lr(R.tagNameCheck,e)&&lr(R.attributeNameCheck,t,e)||t===`is`&&R.allowCustomizedBuiltInElements&&lr(R.tagNameCheck,r);if(ln[t])return!0;let a=ve(r,Lt,``);return w(zt,a)||(t===`src`||t===`xlink:href`||t===`href`)&&e!==`script`&&ye(r,`data:`)===0&&sn[e]||Kt&&!w(It,a)?!0:!r},hr=D({},[`annotation-xml`,`color-profile`,`font-face`,`font-face-format`,`font-face-name`,`font-face-src`,`font-face-uri`,`missing-glyph`]),gr=function(e){return!hr[v(e)]&&w(Rt,e)},_r=function(e,t,n,r){if(N&&typeof d==`object`&&typeof d.getAttributeType==`function`&&!n)switch(d.getAttributeType(e,t)){case`TrustedHTML`:return xt(r);case`TrustedScriptURL`:return Ct(r)}return r},vr=function(e,t,n,r){try{return n?e.setAttributeNS(n,t,r):e.setAttribute(t,r),!rr(e)||(Q(e),!1)}catch(n){return In(t,e),!1}},yr=function(e,t){return V&&w(it,t)?!0:v(e)===`attributename`&&ye(t,`href`)!==-1},br=function(e,n){if($(F.beforeSanitizeAttributes,e,null),fr(e,n))return;let r=gt(e);if(!r||rr(e))return;L=dr(F.uponSanitizeAttribute,L,Vt,Xt);let i={attrName:``,attrValue:``,keepAttr:!0,allowedAttributes:L,forceKeepAttr:void 0},a=r.length,o=Z(M(e));for(;a--;){let n=r[a];if(!n)continue;let s=n.name,c=n.namespaceURI,l=n.value,u=Z(s),d=l,f=s===`value`?d:be(d),p=!1;i.attrName=u,i.attrValue=f,i.keepAttr=!0,i.forceKeepAttr=void 0,$(F.uponSanitizeAttribute,e,i),f=i.attrValue,tn&&(u===`id`||u===`name`)&&ye(f,nn)!==0&&(In(s,e,n),f=nn+f,p=!0),yr(s,f)?In(s,e,n):i.forceKeepAttr||(i.keepAttr?!qt&&w(rt,f)?In(s,e,n):(B&&(f=Qn(f)),mr(o,u,f)?(f=_r(o,u,c,f),f!==d&&vr(e,s,c,f)&&p&&ie(t.removed)):In(s,e,n)):In(s,e,n))}$(F.afterSanitizeAttributes,e,null),fr(e,n)},xr=function(e,t){pr(e,t),br(e,t),ar(e.content)&&Sr(e.content)},Sr=function(e){let t=null,n=Zn(e);for($(F.beforeSanitizeShadowDOM,e,null);t=n.nextNode();)if($(F.uponSanitizeShadowNode,t,null),xr(t,e),O(t)===A.element){let e=Se(t);ar(e)&&(Cr(e),Sr(e))}B&&nr(e),$(F.afterSanitizeShadowDOM,e,null)},Cr=function(e){let t=[{node:e,shadow:null}];for(;t.length>0;){let e=t.pop();if(e.shadow){Sr(e.shadow);continue}let n=e.node,r=O(n)===A.element,i=y(n);if(i)for(let e=i.length-1;e>=0;--e)t.push({node:i[e],shadow:null});if(r){let e=E?E(n):null;if(typeof e==`string`&&Z(e)===`template`){let e=n.content;ar(e)&&t.push({node:e,shadow:null})}}if(r){let e=Se(n);ar(e)&&t.push({node:null,shadow:e},{node:e,shadow:null})}}},wr=function(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i=null,a=null,o=null,s=null;if(pn=!e,pn&&(e=`<!-->`),typeof e!=`string`&&!or(e)&&(e=Ee(e),typeof e!=`string`))throw T(`dirty is not a string, aborting`);if(!t.isSupported)return e;Jt?(I=Yt,L=Xt):Dn(n),wn=Cn,t.removed=[];let c=an&&typeof e!=`string`&&or(e),l=[],u=W,d=G;if(c){Yn(e),l=Bn(e);let t=M(e);if(typeof t==`string`){let n=Z(t);if(!I[n]||Ht[n])throw Un(e,l),T(`root node is forbidden and cannot be sanitized in-place`)}if(rr(e))throw Un(e,l),T(`root node is clobbered and cannot be sanitized in-place`);W=le(),G=pe()}else if(or(e))i=Xn(`<!---->`),a=i.ownerDocument.importNode(e,!0),a.nodeType===A.element&&a.nodeName===`BODY`||a.nodeName===`HTML`?i=a:i.appendChild(a),Cr(i);else{if(!U&&!B&&!H&&e.indexOf(`<`)===-1)return St(e);if(i=Xn(e),!i)return U?null:$t?P:``}i&&Zt&&Q(i.firstChild);let f=c?e:i;try{c&&Cr(e);let t=Zn(f);for(;o=t.nextNode();)xr(o,f);c&&Wn(e,l)}catch(t){throw c&&Un(e,l),t}finally{W=u,G=d}if(c){if(Hn(e,l))throw T(`a node selected for removal could not be safely returned; refusing to sanitize in place`);return B&&$n(e),e}if(U){if(B&&$n(i),Qt)for(s=Ot.call(i.ownerDocument);i.firstChild;)s.appendChild(i.firstChild);else s=i;return(L.shadowroot||L.shadowrootmode)&&(s=At.call(r,s,!0)),s}B&&nr(i);let p=H?i.outerHTML:i.innerHTML;return H&&I[`!doctype`]&&i.ownerDocument&&i.ownerDocument.doctype&&i.ownerDocument.doctype.name&&w(Ze,i.ownerDocument.doctype.name)&&(p=`<!DOCTYPE `+i.ownerDocument.doctype.name+`>
|
| 6 |
+
`+p),St(p)};return t.sanitize=function(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r=wn,i=I,a=L,o=t.removed;wn=null;try{return wr(e,n)}finally{wn=r,r&&(Jt||Dn(r),I=i,L=a,t.removed=o)}},t.setConfig=function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Dn(e),Jt=!0,Yt=I,Xt=L},t.clearConfig=function(){Cn=null,Jt=!1,Yt=null,Xt=null,N=_t,P=``},t.isValidAttribute=function(e,t,n){Cn||Dn({});let r=Z(e),i=Z(t);return typeof n==`string`&&(yr(t,n)||!qt&&w(rt,n))?!1:mr(r,i,n)},t.addHook=function(e,t){typeof t==`function`&&x(F,e)&&ae(F[e],t)},t.removeHook=function(e,t){if(x(F,e)){if(t!==void 0){let n=re(F[e],t);return n===-1?void 0:se(F[e],n,1)[0]}return ie(F[e])}},t.removeHooks=function(e){x(F,e)&&(F[e]=[])},t.removeAllHooks=function(){F=dt()},t}return pt()});
|
| 7 |
+
//# sourceMappingURL=purify.min.js.map
|
app/tools.py
CHANGED
|
@@ -109,6 +109,10 @@ async def _run(argv: list[str], timeout: int, mem_gb: int) -> dict:
|
|
| 109 |
)
|
| 110 |
try:
|
| 111 |
out, err = await asyncio.wait_for(proc.communicate(), timeout)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
except asyncio.TimeoutError:
|
| 113 |
proc.kill()
|
| 114 |
await proc.wait()
|
|
|
|
| 109 |
)
|
| 110 |
try:
|
| 111 |
out, err = await asyncio.wait_for(proc.communicate(), timeout)
|
| 112 |
+
except asyncio.CancelledError: # 使用者按停止:結束子程序
|
| 113 |
+
proc.kill()
|
| 114 |
+
await asyncio.shield(proc.wait())
|
| 115 |
+
raise
|
| 116 |
except asyncio.TimeoutError:
|
| 117 |
proc.kill()
|
| 118 |
await proc.wait()
|