Compare commits
49
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
29be7bd9d7 | ||
|
|
ae9b78c661 | ||
|
|
ca8099b158 | ||
|
|
e55d209f59 | ||
|
|
8096d42926 | ||
|
|
4aa8f01610 | ||
|
|
488734641d | ||
|
|
85984e1ee2 | ||
|
|
71b83bb523 | ||
|
|
45e4720453 | ||
|
|
424bdcbd52 | ||
|
|
bba42ae2ca | ||
|
|
05d03f0836 | ||
|
|
e928fd7cb0 | ||
|
|
3139108838 | ||
|
|
c750393c81 | ||
|
|
6bd1fa48f8 | ||
|
|
6a0aed2611 | ||
|
|
af0575dddd | ||
|
|
25133f90ed | ||
|
|
ac052d6997 | ||
|
|
67d3355f44 | ||
|
|
60d8278610 | ||
|
|
772408fb6e | ||
|
|
111d6d6c90 | ||
|
|
9566cb8151 | ||
|
|
0c9a92aabd | ||
|
|
dab9d8f000 | ||
|
|
d455c2d203 | ||
|
|
da8653e5e9 | ||
|
|
d34b193033 | ||
|
|
c3fdf8b6aa | ||
|
|
b018ba7864 | ||
|
|
c07fc3be58 | ||
|
|
a0195c710b | ||
|
|
71f3cdb694 | ||
|
|
76297a8978 | ||
|
|
0529991ba1 | ||
|
|
87b8d5197b | ||
|
|
2be92e1106 | ||
|
|
f5099345d0 | ||
|
|
67dff34a89 | ||
|
|
8694061068 | ||
|
|
95047678f3 | ||
|
|
baec30398a | ||
|
|
a03fc9b82b | ||
|
|
c21647c642 | ||
|
|
cf21c42b17 | ||
|
|
2e2e47171f |
@@ -10,12 +10,18 @@ skills/*/.deps_installed
|
|||||||
# 本地端(local/):运行期产物与生成的配置都不入库(含密钥,见 local/README.md)
|
# 本地端(local/):运行期产物与生成的配置都不入库(含密钥,见 local/README.md)
|
||||||
local/.runtime/
|
local/.runtime/
|
||||||
local/config.local.yml
|
local/config.local.yml
|
||||||
|
local/config.win.yml
|
||||||
|
# busybox-w32:Windows 启动器下载的 shell 二进制(不进 git)
|
||||||
|
local/bin/
|
||||||
# officecli 二进制资产:skills/office/install.sh 运行期拉取,不进 git
|
# officecli 二进制资产:skills/office/install.sh 运行期拉取,不进 git
|
||||||
skills/office/bin/
|
skills/office/bin/
|
||||||
skills/**/__pycache__/
|
skills/**/__pycache__/
|
||||||
*.log
|
*.log
|
||||||
|
# 读图压缩缓存(会话工作目录 = 仓库根时落在仓库里)
|
||||||
|
.imgcache/
|
||||||
.DS_Store
|
.DS_Store
|
||||||
app/server/version.json
|
app/server/version.json
|
||||||
*.apk
|
*.apk
|
||||||
# 部署配置真身(含密钥,模板见 scripts/deploy.conf.example);
|
# 部署配置真身(含密钥,模板见 scripts/deploy.conf.example);
|
||||||
deploy.conf
|
deploy.conf
|
||||||
|
relay/config.json
|
||||||
|
|||||||
@@ -24,7 +24,8 @@
|
|||||||
| `wxbot/` | 微信 iLink 协议调制解调器(多实例) | 独立容器 `agent-wxbot` |
|
| `wxbot/` | 微信 iLink 协议调制解调器(多实例) | 独立容器 `agent-wxbot` |
|
||||||
| `mcp/` | 同栈 MCP 服务:`web_search` / `image_task` / `video_task` / `asr` | 四个容器,仅内网 |
|
| `mcp/` | 同栈 MCP 服务:`web_search` / `image_task` / `video_task` / `asr` | 四个容器,仅内网 |
|
||||||
| `skills/` | 目录式技能(`SKILL.md` + `run.py`/`run.sh`) | 运行时挂载,`skills/deps` 为依赖层 |
|
| `skills/` | 目录式技能(`SKILL.md` + `run.py`/`run.sh`) | 运行时挂载,`skills/deps` 为依赖层 |
|
||||||
| `local/` | **本地端启动器**:同一份代码跑在本机(不起 Docker / executor),`start.sh` 负责探测、装依赖、守护 | 独立于 compose,见 `docs/local-mode.md` |
|
| `local/` | **本地端启动器**:同一份代码跑在本机(不起 Docker / executor)。`start.sh`(macOS/Linux)与 `start-win.mjs`(Windows)负责探测、装依赖、守护 | 独立于 compose,见 `docs/local-mode.md` |
|
||||||
|
| `tunnel/` | **反向隧道**:服务器端 `server.js` 按 Host / 固定端口 / 通配路由转发,本机 `client.js` 承接 | 独立 compose,见 `tunnel/README.md` |
|
||||||
| `scripts/` | `init.sh` 生成 `.env` + 首次创建 `config.yml`(仅初始管理员);`init_host.sh` 裸机初始化 | 幂等,**不覆盖已有配置** |
|
| `scripts/` | `init.sh` 生成 `.env` + 首次创建 `config.yml`(仅初始管理员);`init_host.sh` 裸机初始化 | 幂等,**不覆盖已有配置** |
|
||||||
| `docs/` | 专题文档:`tool-design.md`(工具接口规范)、`OFFICE.md` | — |
|
| `docs/` | 专题文档:`tool-design.md`(工具接口规范)、`OFFICE.md` | — |
|
||||||
| `tasks/` | **运行时数据**:每个会话一个工作目录 | gitignore |
|
| `tasks/` | **运行时数据**:每个会话一个工作目录 | gitignore |
|
||||||
@@ -38,10 +39,13 @@
|
|||||||
|
|
||||||
```mermaid
|
```mermaid
|
||||||
flowchart TD
|
flowchart TD
|
||||||
|
CORE["agent-core(8090,唯一对外端口)"]
|
||||||
B["浏览器 / PWA"] -->|"HTTP + SSE"| CORE
|
B["浏览器 / PWA"] -->|"HTTP + SSE"| CORE
|
||||||
|
M["手机 / 外网"] -->|"HTTPS"| TUN["tunnel server(19000,仅回环)"]
|
||||||
|
TUN -->|"WebSocket"| TC["tunnel client(本机)"]
|
||||||
|
TC -->|"HTTP"| CORE
|
||||||
W["微信客户端"] --> WXBOT["agent-wxbot(8093,仅内网)"]
|
W["微信客户端"] --> WXBOT["agent-wxbot(8093,仅内网)"]
|
||||||
WXBOT -->|"回调 /wxhook/*(共享 Bearer token)"| CORE
|
WXBOT -->|"回调 /wxhook/*(共享 Bearer token)"| CORE
|
||||||
CORE["agent-core(8090,唯一对外端口)"]
|
|
||||||
CORE --> EXEC["agent-executor(9000 exec / 3100 预览,仅内网)"]
|
CORE --> EXEC["agent-executor(9000 exec / 3100 预览,仅内网)"]
|
||||||
CORE --> MCP["mcp_web_search / mcp_image_task / mcp_video_task / mcp_asr(3000,仅内网)"]
|
CORE --> MCP["mcp_web_search / mcp_image_task / mcp_video_task / mcp_asr(3000,仅内网)"]
|
||||||
CORE -->|"分段投递回复"| WXBOT
|
CORE -->|"分段投递回复"| WXBOT
|
||||||
@@ -59,6 +63,7 @@ flowchart TD
|
|||||||
| 服务 | 端口 | 可见性 |
|
| 服务 | 端口 | 可见性 |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `agent-core` | 8090 | 宿主机映射,**唯一对外** |
|
| `agent-core` | 8090 | 宿主机映射,**唯一对外** |
|
||||||
|
| `tunnel` server | 19000 | 仅 `127.0.0.1`,对外经 nginx 反代 |
|
||||||
| `agent-executor` | 9000(exec)、3100(预览网关) | 仅 `expose`,内网 |
|
| `agent-executor` | 9000(exec)、3100(预览网关) | 仅 `expose`,内网 |
|
||||||
| `agent-wxbot` | 8093 | 仅内网 |
|
| `agent-wxbot` | 8093 | 仅内网 |
|
||||||
| `mcp_*` | 3000 | 仅内网 |
|
| `mcp_*` | 3000 | 仅内网 |
|
||||||
@@ -72,6 +77,7 @@ flowchart TD
|
|||||||
| `./skills/` | `/workspace/skills` | `/workspace/skills:ro` | 技能与共享依赖 |
|
| `./skills/` | `/workspace/skills` | `/workspace/skills:ro` | 技能与共享依赖 |
|
||||||
| `./config.yml` | `/app/config.yml` | 不挂、不读 | 平台密钥、登录密钥 |
|
| `./config.yml` | `/app/config.yml` | 不挂、不读 | 平台密钥、登录密钥 |
|
||||||
| `./app/server/` | `/app/server` | — | 后端代码(**热挂载**) |
|
| `./app/server/` | `/app/server` | — | 后端代码(**热挂载**) |
|
||||||
|
| `./tunnel/data/` | — | — | 隧道服务端配置 `server.yml`(首次启动自动生成,含 token) |
|
||||||
| `./wxbot/data/` | — | `/data`(wxbot) | 微信登录凭证 |
|
| `./wxbot/data/` | — | `/data`(wxbot) | 微信登录凭证 |
|
||||||
|
|
||||||
推论:
|
推论:
|
||||||
@@ -163,6 +169,7 @@ curl -s http://127.0.0.1:8090/api/health
|
|||||||
| 配置默认值 | `app/server/config.js` 的 `DEFAULTS` ↔ `app/config.example.yml` |
|
| 配置默认值 | `app/server/config.js` 的 `DEFAULTS` ↔ `app/config.example.yml` |
|
||||||
| 内置工具 | `app/server/tools/definitions.json` ↔ `app/AGENTS.md` / README 工具表 ↔ `docs/tool-design.md` 规范 |
|
| 内置工具 | `app/server/tools/definitions.json` ↔ `app/AGENTS.md` / README 工具表 ↔ `docs/tool-design.md` 规范 |
|
||||||
| 新增服务 / 端口 / 卷 | `docker-compose.yml` ↔ `README.md` 的部署与安全章节 |
|
| 新增服务 / 端口 / 卷 | `docker-compose.yml` ↔ `README.md` 的部署与安全章节 |
|
||||||
|
| 隧道 token | `tunnel/data/server.yml`(自动生成)↔ `tunnel/client.yml`(手写),两边必须一致 |
|
||||||
| 新增环境变量 | compose ↔ README「环境变量」 |
|
| 新增环境变量 | compose ↔ README「环境变量」 |
|
||||||
| 发版号 | `app/package.json` 的 `version` ↔ `app/server/routes/system.js` 的 `VERSION` 字面量(两者不自动同步) |
|
| 发版号 | `app/package.json` 的 `version` ↔ `app/server/routes/system.js` 的 `VERSION` 字面量(两者不自动同步) |
|
||||||
| 技能格式 | `skills/README.md` ↔ `app/server/tools/skills.js` 的解析 |
|
| 技能格式 | `skills/README.md` ↔ `app/server/tools/skills.js` 的解析 |
|
||||||
@@ -180,6 +187,10 @@ curl -s http://127.0.0.1:8090/api/health
|
|||||||
由 `server.js` 传函数进去。
|
由 `server.js` 传函数进去。
|
||||||
- 前端是**无构建的经典脚本**:新增文件要同时改 `app/server/public/index.html` 的 `<script>`
|
- 前端是**无构建的经典脚本**:新增文件要同时改 `app/server/public/index.html` 的 `<script>`
|
||||||
顺序(共享全局作用域,顺序即依赖)。
|
顺序(共享全局作用域,顺序即依赖)。
|
||||||
|
- 前端图标统一走 `index.html` 顶部的 `<symbol>` sprite:引用写成
|
||||||
|
`<svg class="…" viewBox="0 0 24 24"><use href="#i-xxx"/></svg>`,形状只改 sprite 里那一行,
|
||||||
|
尺寸与描边归各处 CSS(`.ic` / `.tree-act svg` 等)。加图标先加 `<symbol id="i-xxx">`,
|
||||||
|
漏了不报错、界面只是空白。
|
||||||
|
|
||||||
## 常见任务去哪改
|
## 常见任务去哪改
|
||||||
|
|
||||||
@@ -193,5 +204,6 @@ curl -s http://127.0.0.1:8090/api/health
|
|||||||
| 改微信投递 | `app/server/wechat.js`(业务)+ `app/server/routes/wechat.js`(HTTP/鉴权) |
|
| 改微信投递 | `app/server/wechat.js`(业务)+ `app/server/routes/wechat.js`(HTTP/鉴权) |
|
||||||
| 改语音输入 | `app/server/public/js/voice.js`(录音与插入)+ `app/server/routes/asr.js`(代理)+ `mcp/asr/`(转写);客户端桥契约见 `docs/voice-input.md` |
|
| 改语音输入 | `app/server/public/js/voice.js`(录音与插入)+ `app/server/routes/asr.js`(代理)+ `mcp/asr/`(转写);客户端桥契约见 `docs/voice-input.md` |
|
||||||
| 改隔离执行 | `executor/server.js`(先读顶部安全模型注释) |
|
| 改隔离执行 | `executor/server.js`(先读顶部安全模型注释) |
|
||||||
|
| 改隧道路由 / 转发 | `tunnel/server.js`(按 Host / 端口匹配)+ `tunnel/client.js`(本地服务映射) |
|
||||||
| 加同栈 MCP 服务 | `mcp/<name>/` + `docker-compose.yml` + `config.yml` 的 `mcp_servers` |
|
| 加同栈 MCP 服务 | `mcp/<name>/` + `docker-compose.yml` + `config.yml` 的 `mcp_servers` |
|
||||||
| 加技能 | `skills/<name>/`(`SKILL.md` + `run.py`),见 `skills/README.md` |
|
| 加技能 | `skills/<name>/`(`SKILL.md` + `run.py`),见 `skills/README.md` |
|
||||||
|
|||||||
@@ -28,6 +28,8 @@ macOS / Linux,Node 20+,不需要 Docker:
|
|||||||
|
|
||||||
首次运行会让你选一个工作目录(技能、会话、数据库都在里面)。命令直接在本机执行,没有沙箱隔离,只监听 `127.0.0.1`。
|
首次运行会让你选一个工作目录(技能、会话、数据库都在里面)。命令直接在本机执行,没有沙箱隔离,只监听 `127.0.0.1`。
|
||||||
|
|
||||||
|
需要从外网访问时,配好 [`tunnel/client.yml`](tunnel/README.md) 后 `start.sh` 会一并拉起隧道 client;未配置则跳过。
|
||||||
|
|
||||||
## 组成
|
## 组成
|
||||||
|
|
||||||
| 目录 | 说明 |
|
| 目录 | 说明 |
|
||||||
@@ -38,6 +40,7 @@ macOS / Linux,Node 20+,不需要 Docker:
|
|||||||
| [`mcp/`](mcp/README.md) | 四个 MCP 服务:网页搜索、图片生成、视频生成、语音转写 |
|
| [`mcp/`](mcp/README.md) | 四个 MCP 服务:网页搜索、图片生成、视频生成、语音转写 |
|
||||||
| [`skills/`](skills/README.md) | 内置技能 |
|
| [`skills/`](skills/README.md) | 内置技能 |
|
||||||
| [`local/`](local/README.md) | 本机模式启动器 |
|
| [`local/`](local/README.md) | 本机模式启动器 |
|
||||||
|
| [`tunnel/`](tunnel/README.md) | 反向隧道:把本机服务经服务器中转,供外网访问 |
|
||||||
|
|
||||||
## 配置
|
## 配置
|
||||||
|
|
||||||
@@ -68,6 +71,7 @@ docker compose up -d --build
|
|||||||
## 安全
|
## 安全
|
||||||
|
|
||||||
- 对外只开 agent-core 一个端口,其余服务只在 Docker 内网
|
- 对外只开 agent-core 一个端口,其余服务只在 Docker 内网
|
||||||
|
- 隧道只经服务器 nginx(TLS)对外,宿主机端口仅绑 `127.0.0.1`;`server.yml` 与 `client.yml` 的 token 必须一致
|
||||||
- 命令在 executor 容器里执行,只挂当前会话目录,根文件系统只读
|
- 命令在 executor 容器里执行,只挂当前会话目录,根文件系统只读
|
||||||
- 单租户设计:除管理员接口外不做用户级资源隔离,不要开放给互不信任的人
|
- 单租户设计:除管理员接口外不做用户级资源隔离,不要开放给互不信任的人
|
||||||
- `config.yml`、`.env`、`wxbot/data/` 存密钥,已加入 `.gitignore`
|
- `config.yml`、`.env`、`wxbot/data/` 存密钥,已加入 `.gitignore`
|
||||||
|
|||||||
+12
-1
@@ -51,7 +51,7 @@ AGENT_CONFIG=./config.yml node server/server.js
|
|||||||
| `server/wechat.js` | 微信绑定、媒体落盘、上下文注入、SSE→微信分段投递、任务通知 |
|
| `server/wechat.js` | 微信绑定、媒体落盘、上下文注入、SSE→微信分段投递、任务通知 |
|
||||||
| `server/routes/channel.js` | 文本命令层(`/new` `/switch` `/think` …),微信与外部接入端共用 |
|
| `server/routes/channel.js` | 文本命令层(`/new` `/switch` `/think` …),微信与外部接入端共用 |
|
||||||
| `server/routes/*.js` | HTTP API,按资源分文件 |
|
| `server/routes/*.js` | HTTP API,按资源分文件 |
|
||||||
| `server/sse.js` | 按会话分组的 SSE 总线(`addClient`/`emit`/`onInternal`) |
|
| `server/sse.js` | 按会话分组的 SSE 总线(`addClient`/`emit`/`onInternal`);`assistant_delta` / `reasoning_delta` / `tool_call_args` 攒 50ms 或 8 条合并写入 |
|
||||||
| `server/auth.js` | HMAC cookie 登录、Basic 兜底、`requireAdmin`、免认证路径 |
|
| `server/auth.js` | HMAC cookie 登录、Basic 兜底、`requireAdmin`、免认证路径 |
|
||||||
| `server/memory.js` | 长期记忆(日记碎片)读写与检索,仅依赖 `time.js` |
|
| `server/memory.js` | 长期记忆(日记碎片)读写与检索,仅依赖 `time.js` |
|
||||||
| `server/time.js` | 业务时区单一入口:`TZ`、`dayString`、`stampString`、`fmtTime`、`fmtIso` |
|
| `server/time.js` | 业务时区单一入口:`TZ`、`dayString`、`stampString`、`fmtTime`、`fmtIso` |
|
||||||
@@ -59,6 +59,7 @@ AGENT_CONFIG=./config.yml node server/server.js
|
|||||||
| `server/public-files.js` | `mint_public_link` 的短链签发与解析(进程内 Map) |
|
| `server/public-files.js` | `mint_public_link` 的短链签发与解析(进程内 Map) |
|
||||||
| `server/download-token.js` | 浏览器下载链接的 HMAC 签名(密钥进程内随机) |
|
| `server/download-token.js` | 浏览器下载链接的 HMAC 签名(密钥进程内随机) |
|
||||||
| `server/remote-exec.js` | 调 `agent-executor` 的 `/exec`(SSE)与预览槽清理 |
|
| `server/remote-exec.js` | 调 `agent-executor` 的 `/exec`(SSE)与预览槽清理 |
|
||||||
|
| `server/shell.js` | **执行后端**:解析用哪个 POSIX shell 跑命令(POSIX 直接 `/bin/sh`;Windows 依次 git-bash → busybox-w32)、跨平台杀进程树。平台差异只允许出现在这里 |
|
||||||
| `server/log.js` | 分级日志 `log.debug/info/warn/error(category, ...)` |
|
| `server/log.js` | 分级日志 `log.debug/info/warn/error(category, ...)` |
|
||||||
| `server/balance.js` | 平台余额查询适配器(按 `platform.type` 分发) |
|
| `server/balance.js` | 平台余额查询适配器(按 `platform.type` 分发) |
|
||||||
| `server/version.js` | git commit/date:优先读 `version.json`(post-commit 钩子生成),宿主机有 git 时兜底 `git rev-parse`;页面版本号另外由 `routes/system.js` 的 `VERSION` 字面量决定 |
|
| `server/version.js` | git commit/date:优先读 `version.json`(post-commit 钩子生成),宿主机有 git 时兜底 `git rev-parse`;页面版本号另外由 `routes/system.js` 的 `VERSION` 字面量决定 |
|
||||||
@@ -211,6 +212,11 @@ IM 用户在实时对话,回合中插话应当“当前这步跑完就插”
|
|||||||
`{content, reasoning, tool_calls, finish_reason, usage, aborted, sseFrames}`;正文开头混入的
|
`{content, reasoning, tool_calls, finish_reason, usage, aborted, sseFrames}`;正文开头混入的
|
||||||
`<think>` 块会被 `splitInlineThinking` 剥离到 reasoning。
|
`<think>` 块会被 `splitInlineThinking` 剥离到 reasoning。
|
||||||
|
|
||||||
|
增量上下文(模型配了 `store: true` 且带 `opts.context_id`):只发上次之后新增的消息,带
|
||||||
|
`X-Context-Id` / `X-Context-Hash`;relay 回 409 说明缓存对不上(压缩、relay 重启、TTL 过期),
|
||||||
|
改发全量重试**一次**。指针存 `ctxState`(进程内存,只存 hash + 条数),进程重启即失效 →
|
||||||
|
下一轮自动全量。上游仍然是全量,语义不变。
|
||||||
|
|
||||||
## 工具层
|
## 工具层
|
||||||
|
|
||||||
- 工具全集 = `definitions.json`(14 个内置)+ MCP 发现结果;再依次叠 profile 的 `tools_allow`
|
- 工具全集 = `definitions.json`(14 个内置)+ MCP 发现结果;再依次叠 profile 的 `tools_allow`
|
||||||
@@ -354,6 +360,8 @@ preview-proxy.mount(末尾兜底)
|
|||||||
JS/CSS 改动不需要。
|
JS/CSS 改动不需要。
|
||||||
- 另有 `login.html`、`memory.html`(日记调试页)。
|
- 另有 `login.html`、`memory.html`(日记调试页)。
|
||||||
- API 调用统一走 `core.js` 的 `req()`;SSE 用 `EventSource` + 前端看门狗。
|
- API 调用统一走 `core.js` 的 `req()`;SSE 用 `EventSource` + 前端看门狗。
|
||||||
|
- 文件面板(`files.js`)按目录懒加载:只请求 `GET /api/sessions/:id/tree?dir=<rel>` 的当前层,
|
||||||
|
进入子目录才拉下一层;会话详情接口不返回全量 `files`。
|
||||||
|
|
||||||
## 扩展指南
|
## 扩展指南
|
||||||
|
|
||||||
@@ -396,6 +404,9 @@ preview-proxy.mount(末尾兜底)
|
|||||||
|
|
||||||
## 陷阱清单(都是踩过的)
|
## 陷阱清单(都是踩过的)
|
||||||
|
|
||||||
|
- **平台差异只允许出现在 `server/shell.js`**:`terminal` / 技能 / `engine.killRunProcs` 一律走
|
||||||
|
`shell.spawnShell` / `shell.killTree`,上层不写 `process.platform` 分支。POSIX 分支的行为
|
||||||
|
(`/bin/sh -c` + 进程组 + `kill(-pid)`)不能变——它是「模型按 POSIX 写就一定能跑」的保证。
|
||||||
- **循环依赖**:`engine` 绝不 `require('./wechat')` 或 `require('./scheduler')`,否则拿到半成品
|
- **循环依赖**:`engine` 绝不 `require('./wechat')` 或 `require('./scheduler')`,否则拿到半成品
|
||||||
exports。通知面/engine 引用一律由 `server.js` 注入。`executor → scheduler` 是单向的,安全。
|
exports。通知面/engine 引用一律由 `server.js` 注入。`executor → scheduler` 是单向的,安全。
|
||||||
- **tool_call 配对**:删 assistant 必须连带删该轮的 `tool` 回执;删单条 `tool` 回执必须从父
|
- **tool_call 配对**:删 assistant 必须连带删该轮的 `tool` 回执;删单条 `tool` 回执必须从父
|
||||||
|
|||||||
@@ -33,6 +33,9 @@ log_level: "info" # debug < info < warn < error
|
|||||||
terminal:
|
terminal:
|
||||||
default_timeout_ms: 30000 # 命令默认超时(ms)
|
default_timeout_ms: 30000 # 命令默认超时(ms)
|
||||||
max_output_chars: 10000 # 回传模型的最大输出字符数
|
max_output_chars: 10000 # 回传模型的最大输出字符数
|
||||||
|
# shell: '' # 跑命令的 POSIX shell;空 = 自动探测
|
||||||
|
# POSIX:/bin/sh;Windows:git-bash → busybox-w32
|
||||||
|
# env AGENT_SHELL 优先级更高,AGENT_SHELL_ARGS 可改参数模板
|
||||||
|
|
||||||
fetch:
|
fetch:
|
||||||
timeout_ms: 30000 # 抓取总超时(ms),覆盖响应头到 body 读完
|
timeout_ms: 30000 # 抓取总超时(ms),覆盖响应头到 body 读完
|
||||||
|
|||||||
+11
-1
@@ -76,7 +76,9 @@ const DEFAULTS = {
|
|||||||
db_path: '',
|
db_path: '',
|
||||||
// executor / 微信接入(wxbot)均不占配置字段:两组件接线纯 env(compose 经根 .env 注入,见 parseAndValidate);
|
// executor / 微信接入(wxbot)均不占配置字段:两组件接线纯 env(compose 经根 .env 注入,见 parseAndValidate);
|
||||||
// 本配置文件内含密钥,只给 core 进程读,executor/wxbot 一律不挂不读。
|
// 本配置文件内含密钥,只给 core 进程读,executor/wxbot 一律不挂不读。
|
||||||
terminal: { default_timeout_ms: 30000, max_output_chars: 10000 },
|
// terminal.shell:跑命令用的 POSIX shell(空 = 自动探测:POSIX 直接 /bin/sh;Windows 依次找
|
||||||
|
// git-bash、busybox-w32)。env AGENT_SHELL 优先级更高,AGENT_SHELL_ARGS 覆盖参数模板(默认 -c)。
|
||||||
|
terminal: { default_timeout_ms: 30000, max_output_chars: 10000, shell: '' },
|
||||||
// fetch:timeout_ms 覆盖请求发出到 body 读完的全生命周期;max_bytes 为流式抓取字节上限(超限即断开)。
|
// fetch:timeout_ms 覆盖请求发出到 body 读完的全生命周期;max_bytes 为流式抓取字节上限(超限即断开)。
|
||||||
// 下载与返回两上限解耦:下载不进上下文可宽松,返回默认收紧(max_chars),模型显式传 max_chars 时
|
// 下载与返回两上限解耦:下载不进上下文可宽松,返回默认收紧(max_chars),模型显式传 max_chars 时
|
||||||
// 夹在 max_chars_hard 硬帽内;超窗尾部提示 offset,续读走 ctx.run 上的回合缓存不重抓。
|
// 夹在 max_chars_hard 硬帽内;超窗尾部提示 offset,续读走 ctx.run 上的回合缓存不重抓。
|
||||||
@@ -102,6 +104,10 @@ const DEFAULTS = {
|
|||||||
{ tool: 'fetch', side: 'result', rounds: 2, turns: 1, status_regex: '^HTTP (\\d{3})' },
|
{ tool: 'fetch', side: 'result', rounds: 2, turns: 1, status_regex: '^HTTP (\\d{3})' },
|
||||||
{ tool: 'read_file', side: 'result', rounds: 2, turns: 1 },
|
{ tool: 'read_file', side: 'result', rounds: 2, turns: 1 },
|
||||||
{ tool: 'web_search', side: 'result', rounds: 2, turns: 1 },
|
{ tool: 'web_search', side: 'result', rounds: 2, turns: 1 },
|
||||||
|
// terminal 输出占了会话上下文的大头(实测 69%),但单条都不大(最大 10KB),
|
||||||
|
// 所以阈值降到 1500(实测拐点:>1500 裁 43%,>2000 只裁 33%)。
|
||||||
|
// rounds:5 比其它规则更晚动手——terminal 输出经常还要回头看;turns:2 保证当前回合绝不裁。
|
||||||
|
{ tool: 'terminal', side: 'result', rounds: 5, turns: 2, min_chars: 1500 },
|
||||||
],
|
],
|
||||||
} },
|
} },
|
||||||
// 大图上传预处理(浏览器端 canvas 压缩,参数经 /api/system/status 下发前端)。
|
// 大图上传预处理(浏览器端 canvas 压缩,参数经 /api/system/status 下发前端)。
|
||||||
@@ -236,6 +242,9 @@ function normalizePlatforms(rawPlatforms, profileNames) {
|
|||||||
// 非空时发请求前给历史 assistant 行挂该字段;空(缺省)= 不回传。纯发送侧旋钮,
|
// 非空时发请求前给历史 assistant 行挂该字段;空(缺省)= 不回传。纯发送侧旋钮,
|
||||||
// 与接收解析无关(接收早已兼容 reasoning/reasoning_content 双名)。
|
// 与接收解析无关(接收早已兼容 reasoning/reasoning_content 双名)。
|
||||||
reasoning_ack_field: typeof m.reasoning_ack_field === 'string' ? m.reasoning_ack_field.trim() : '',
|
reasoning_ack_field: typeof m.reasoning_ack_field === 'string' ? m.reasoning_ack_field.trim() : '',
|
||||||
|
// 选填:该模型的请求走增量上下文(context relay),只有配合 relay 生效。
|
||||||
|
// 不配 = 每轮重传全量,和以前完全一样。
|
||||||
|
store: m.store === true,
|
||||||
// 选填:自动压缩阈值(用户自定义的「上下文用量线」,**不是**模型真实窗口)。
|
// 选填:自动压缩阈值(用户自定义的「上下文用量线」,**不是**模型真实窗口)。
|
||||||
// 回合内 In token 峰值达到它即自动压缩上下文(见 engine.runLoopInner 循环顶部);0/未配 = 不启用。
|
// 回合内 In token 峰值达到它即自动压缩上下文(见 engine.runLoopInner 循环顶部);0/未配 = 不启用。
|
||||||
max_context: Math.max(0, parseInt(m.max_context, 10) || 0),
|
max_context: Math.max(0, parseInt(m.max_context, 10) || 0),
|
||||||
@@ -363,6 +372,7 @@ function parseAndValidate(rawText, configPath) {
|
|||||||
extra_params: m.extra_params, thinking_params: m.thinking_params,
|
extra_params: m.extra_params, thinking_params: m.thinking_params,
|
||||||
reasoning_ack_field: m.reasoning_ack_field,
|
reasoning_ack_field: m.reasoning_ack_field,
|
||||||
max_context: m.max_context,
|
max_context: m.max_context,
|
||||||
|
store: m.store,
|
||||||
profile: m.profile,
|
profile: m.profile,
|
||||||
url: p.url, api_key: k.api_key, platform: p.name, type: p.type, concurrency: k.concurrency,
|
url: p.url, api_key: k.api_key, platform: p.name, type: p.type, concurrency: k.concurrency,
|
||||||
platform_index: pi, key_index: ki, model_index: mi,
|
platform_index: pi, key_index: ki, model_index: mi,
|
||||||
|
|||||||
+40
-4
@@ -2,11 +2,13 @@
|
|||||||
// 单进程内存模型:JS 单线程 + better-sqlite3 同步 API,不存在跨进程竞争。
|
// 单进程内存模型:JS 单线程 + better-sqlite3 同步 API,不存在跨进程竞争。
|
||||||
const fs = require('fs');
|
const fs = require('fs');
|
||||||
const path = require('path');
|
const path = require('path');
|
||||||
const { buildMessages, callModel, encodeBlocks, decodeBlocks, compressMessages, titleMessages, setProfilePrompts, patchImageReceipt } = require('./llm');
|
const { buildMessages, callModel, encodeBlocks, decodeBlocks, compressMessages, titleMessages, setProfilePrompts, patchImageReceipt, invalidateContext } = require('./llm');
|
||||||
|
const { instanceId } = require('./instance');
|
||||||
const { executeTool, resolveInTask } = require('./tools/executor');
|
const { executeTool, resolveInTask } = require('./tools/executor');
|
||||||
const publicFiles = require('./public-files');
|
const publicFiles = require('./public-files');
|
||||||
const mcp = require('./mcp');
|
const mcp = require('./mcp');
|
||||||
const rexec = require('./remote-exec');
|
const rexec = require('./remote-exec');
|
||||||
|
const shell = require('./shell'); // 执行后端:killTree 的平台差异(进程组 / taskkill)不往引擎里渗
|
||||||
const log = require('./log');
|
const log = require('./log');
|
||||||
const profile = require('./user-profile');
|
const profile = require('./user-profile');
|
||||||
const memory = require('./memory');
|
const memory = require('./memory');
|
||||||
@@ -109,6 +111,21 @@ function loadHistory(sessionId) {
|
|||||||
return db.prepare('SELECT * FROM messages WHERE session_id = ? ORDER BY id').all(sessionId);
|
return db.prepare('SELECT * FROM messages WHERE session_id = ? ORDER BY id').all(sessionId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 已被压缩掉的行数 = 「压缩代数」。压缩时会把摘要之前的所有行标成 archived,
|
||||||
|
// 所以这个数单调递增;用它做增量上下文的 id 后缀,压缩后 id 自变,relay 缓存自然失效。
|
||||||
|
function archivedCount(history) {
|
||||||
|
let n = 0;
|
||||||
|
for (const r of history || []) if (r.type === 'archived') n++;
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 增量上下文 id 的拼法(与 llm.js 的 X-Context-Id 一致):<core_id>:<user>:<session_id>:<archived_cnt>。
|
||||||
|
// 删除消息后要把这个 key 作废,让下一轮走全量重建。
|
||||||
|
function contextIdOf(session) {
|
||||||
|
return instanceId(cfg.data_root) + ':' + (session.user || '-') + ':' + session.id +
|
||||||
|
':' + archivedCount(session.history);
|
||||||
|
}
|
||||||
|
|
||||||
function saveMessage(sessionId, msg) {
|
function saveMessage(sessionId, msg) {
|
||||||
const info = db.prepare(
|
const info = db.prepare(
|
||||||
'INSERT INTO messages (session_id, role, content, reasoning, tool_calls, tool_call_id, name, type, is_error, usage, created_at) VALUES (?,?,?,?,?,?,?,?,?,?,?)'
|
'INSERT INTO messages (session_id, role, content, reasoning, tool_calls, tool_call_id, name, type, is_error, usage, created_at) VALUES (?,?,?,?,?,?,?,?,?,?,?)'
|
||||||
@@ -552,9 +569,8 @@ function killRunProcs(run) {
|
|||||||
for (const proc of run.procs) {
|
for (const proc of run.procs) {
|
||||||
// 远端 executor 任务句柄(remote-exec.js):发 DELETE 取消,不能本地 kill。
|
// 远端 executor 任务句柄(remote-exec.js):发 DELETE 取消,不能本地 kill。
|
||||||
if (typeof proc.remoteKill === 'function') { try { proc.remoteKill(); } catch (_) {} continue; }
|
if (typeof proc.remoteKill === 'function') { try { proc.remoteKill(); } catch (_) {} continue; }
|
||||||
try { process.kill(-proc.pid, 'SIGKILL'); } catch (_) {
|
// 平台差异交给执行后端:POSIX 杀进程组,Windows 走 taskkill /T。
|
||||||
try { proc.kill('SIGKILL'); } catch (__) {}
|
shell.killTree(proc);
|
||||||
}
|
|
||||||
}
|
}
|
||||||
run.procs.clear();
|
run.procs.clear();
|
||||||
}
|
}
|
||||||
@@ -859,6 +875,10 @@ async function runLoopInner(sessionId, run) {
|
|||||||
lastErr = err;
|
lastErr = err;
|
||||||
const retriable = !err.upstream_status || err.upstream_status === 429 || err.upstream_status >= 500;
|
const retriable = !err.upstream_status || err.upstream_status === 429 || err.upstream_status >= 500;
|
||||||
if (!retriable || attempt === cfg.agent.max_retries) break;
|
if (!retriable || attempt === cfg.agent.max_retries) break;
|
||||||
|
// 重试用的是同一份 messages(数组一字未变),所以增量上下文会发空 body,
|
||||||
|
// 只花百来字节就能让 relay 用缓存重发。这行日志是用来对上那笔账的。
|
||||||
|
log.warn('model', sessionId + ' 第 ' + (attempt + 1) + '/' + cfg.agent.max_retries +
|
||||||
|
' 次重试:' + String(err.message || '').slice(0, 100));
|
||||||
await sleep(2000 * (attempt + 1));
|
await sleep(2000 * (attempt + 1));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1159,6 +1179,11 @@ async function streamAssistant(sessionId, run, session, messages, tools) {
|
|||||||
// key_slot 定位会话占用的具体 key 副本(model_id 只到「平台/模型」)
|
// key_slot 定位会话占用的具体 key 副本(model_id 只到「平台/模型」)
|
||||||
const result = await callModel(cfg, session.model_id, messages, tools, {
|
const result = await callModel(cfg, session.model_id, messages, tools, {
|
||||||
key_slot: session.model_slot,
|
key_slot: session.model_slot,
|
||||||
|
// 增量上下文用:<core_id>:<user>:<session_id>:<archived_cnt>。
|
||||||
|
// archived_cnt = 已被压缩掉的行数,它就是「压缩代数」:压缩后自增 → id 自变 →
|
||||||
|
// relay 找不到缓存并回 409 → 发全量重建。裁剪不改它(只换内容不删行),
|
||||||
|
// 所以裁剪不会打断增量。只有带 store: true 的模型才真的用它(llm.js 判断)。
|
||||||
|
context_id: contextIdOf(session),
|
||||||
signal: run.abortController.signal,
|
signal: run.abortController.signal,
|
||||||
shouldCancel: () => run.cancelled,
|
shouldCancel: () => run.cancelled,
|
||||||
onText: delta => bus.emit(sessionId, 'assistant_delta', { text: delta }),
|
onText: delta => bus.emit(sessionId, 'assistant_delta', { text: delta }),
|
||||||
@@ -1835,7 +1860,9 @@ function clearSessionMessages(sessionId) {
|
|||||||
}
|
}
|
||||||
runs.delete(sessionId);
|
runs.delete(sessionId);
|
||||||
clearPendings(sessionId); // 历史清零:队列里的消息也没了着落,一并作废
|
clearPendings(sessionId); // 历史清零:队列里的消息也没了着落,一并作废
|
||||||
|
const cid = contextIdOf(session); // 删行不影响 archived_cnt,先算后算等价
|
||||||
db.prepare('DELETE FROM messages WHERE session_id = ?').run(sessionId);
|
db.prepare('DELETE FROM messages WHERE session_id = ?').run(sessionId);
|
||||||
|
invalidateContext(cid); // 历史清零:增量指针也得跟着作废
|
||||||
wipeSessionTmp(sessionId); // 会话级 /tmp 随清空一并抹掉(尽力而为,失败只记日志不阻断)
|
wipeSessionTmp(sessionId); // 会话级 /tmp 随清空一并抹掉(尽力而为,失败只记日志不阻断)
|
||||||
autoCompressProposed.delete(sessionId); // 历史清零,恢复自动压缩提议额度
|
autoCompressProposed.delete(sessionId); // 历史清零,恢复自动压缩提议额度
|
||||||
// 标题随历史一并清零:旧标题描述的是已删除的对话,留着会让新对话文不对题;
|
// 标题随历史一并清零:旧标题描述的是已删除的对话,留着会让新对话文不对题;
|
||||||
@@ -1871,6 +1898,7 @@ function deleteMessage(sessionId, messageId) {
|
|||||||
const row = db.prepare('SELECT * FROM messages WHERE id = ? AND session_id = ?').get(messageId, sessionId);
|
const row = db.prepare('SELECT * FROM messages WHERE id = ? AND session_id = ?').get(messageId, sessionId);
|
||||||
if (!row) throw Object.assign(new Error('消息不存在'), { status_code: 404 });
|
if (!row) throw Object.assign(new Error('消息不存在'), { status_code: 404 });
|
||||||
if (row.role === 'tool') return deleteToolMessage(sessionId, row);
|
if (row.role === 'tool') return deleteToolMessage(sessionId, row);
|
||||||
|
const cid = contextIdOf(session); // 删之前先算:archived_cnt 不受删行影响,两者等价,但先算更直观
|
||||||
let removed = 0;
|
let removed = 0;
|
||||||
if (row.tool_calls) {
|
if (row.tool_calls) {
|
||||||
let calls = [];
|
let calls = [];
|
||||||
@@ -1882,6 +1910,9 @@ function deleteMessage(sessionId, messageId) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
db.prepare('DELETE FROM messages WHERE id = ?').run(messageId);
|
db.prepare('DELETE FROM messages WHERE id = ?').run(messageId);
|
||||||
|
// 删中间一条:后面的行位置全变,但末尾行 id 没变,锚点查不出来——主动作废增量指针,
|
||||||
|
// 下一轮改发 X-Context-Reset 全量重建,否则 relay 缓存里还留着被删那行,增量拼出来会错位。
|
||||||
|
invalidateContext(cid);
|
||||||
return { ok: true, id: messageId, removed: removed + 1 };
|
return { ok: true, id: messageId, removed: removed + 1 };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1899,6 +1930,8 @@ function editUserMessage(sessionId, messageId, content, opts) {
|
|||||||
// 先确保能开跑:无可用模型时抛 503,避免删完历史却发不出去
|
// 先确保能开跑:无可用模型时抛 503,避免删完历史却发不出去
|
||||||
ensureBinding(session);
|
ensureBinding(session);
|
||||||
const removed = db.prepare('DELETE FROM messages WHERE session_id = ? AND id >= ?').run(sessionId, messageId).changes;
|
const removed = db.prepare('DELETE FROM messages WHERE session_id = ? AND id >= ?').run(sessionId, messageId).changes;
|
||||||
|
// 尾部截断:锚点本就能查出,但这里紧接着就重新发消息,一并作废指针更直接
|
||||||
|
invalidateContext(contextIdOf(session));
|
||||||
const r = postUserMessage(sessionId, content, opts);
|
const r = postUserMessage(sessionId, content, opts);
|
||||||
log.info('msg', sessionId + ' 编辑消息 ' + messageId + ',丢弃其后 ' + Math.max(0, removed - 1) + ' 条历史');
|
log.info('msg', sessionId + ' 编辑消息 ' + messageId + ',丢弃其后 ' + Math.max(0, removed - 1) + ' 条历史');
|
||||||
return Object.assign({ removed: removed }, r);
|
return Object.assign({ removed: removed }, r);
|
||||||
@@ -1929,6 +1962,9 @@ function deleteToolMessage(sessionId, row) {
|
|||||||
}
|
}
|
||||||
break; // id 唯一,命中即止
|
break; // id 唯一,命中即止
|
||||||
}
|
}
|
||||||
|
// 同上:回执被删、父调用也改过 tool_calls,历史已被控——作废增量指针
|
||||||
|
const s = getSession(sessionId);
|
||||||
|
if (s) invalidateContext(contextIdOf(s));
|
||||||
return { ok: true, id: row.id, removed };
|
return { ok: true, id: row.id, removed };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+18
-1
@@ -47,7 +47,24 @@ async function ensureRepo(dir) {
|
|||||||
let head = '';
|
let head = '';
|
||||||
try { branch = (await run(root, ['symbolic-ref', '--short', '-q', 'HEAD'])).trim(); } catch (_) { /* detached */ }
|
try { branch = (await run(root, ['symbolic-ref', '--short', '-q', 'HEAD'])).trim(); } catch (_) { /* detached */ }
|
||||||
try { head = (await run(root, ['rev-parse', '--short', 'HEAD'])).trim(); } catch (_) { /* 空仓库 */ }
|
try { head = (await run(root, ['rev-parse', '--short', 'HEAD'])).trim(); } catch (_) { /* 空仓库 */ }
|
||||||
return { root, branch: branch || (head ? 'detached' : ''), head };
|
// remote:列表里要能看出这个仓库推到哪。只取第一条 fetch(origin 惯例在最前);
|
||||||
|
// URL 里的 user:pass 脱敏,免得面板上直接暴露凭据。
|
||||||
|
let remote = null;
|
||||||
|
try {
|
||||||
|
const first = (await run(root, ['remote', '-v'])).split('\n').filter(Boolean)[0] || '';
|
||||||
|
const m = /^(\S+)\s+(\S+)\s+\(fetch\)/.exec(first);
|
||||||
|
if (m) remote = { name: m[1], url: m[2].replace(/\/\/[^/@]+@/, '//***@') };
|
||||||
|
} catch (_) { /* 没配 remote */ }
|
||||||
|
// upstream:列表要把 origin/master 标在它指向的那条提交上,一眼看出本地领先几条。
|
||||||
|
// 优先当前分支的 upstream,没配就回退 origin/master。
|
||||||
|
let upstream = null;
|
||||||
|
try {
|
||||||
|
const ref = (await run(root, ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}'])).trim();
|
||||||
|
if (ref) upstream = { ref, id: (await run(root, ['rev-parse', ref])).trim() };
|
||||||
|
} catch (_) {
|
||||||
|
try { upstream = { ref: 'origin/master', id: (await run(root, ['rev-parse', 'origin/master'])).trim() }; } catch (__) { upstream = null; }
|
||||||
|
}
|
||||||
|
return { root, branch: branch || (head ? 'detached' : ''), head, remote, upstream };
|
||||||
}
|
}
|
||||||
|
|
||||||
// 把一个整段 diff 按 `diff --git` 切开,键是文件路径。
|
// 把一个整段 diff 按 `diff --git` 切开,键是文件路径。
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
'use strict';
|
||||||
|
// 实例标识:跨 core 隔离用,作 relay 的 X-Context-Id 前缀。
|
||||||
|
// 首次启动生成并落盘到 <data_root>/instance-id,之后只读同一个值。
|
||||||
|
// 删了数据目录会换新 id —— 旧缓存成孤儿,由 relay 的 TTL 自行清理,不影响正确性。
|
||||||
|
const fs = require('node:fs');
|
||||||
|
const path = require('node:path');
|
||||||
|
const crypto = require('node:crypto');
|
||||||
|
|
||||||
|
const cache = new Map(); // dataRoot -> id
|
||||||
|
|
||||||
|
function instanceId(dataRoot) {
|
||||||
|
const root = path.resolve(String(dataRoot || '.'));
|
||||||
|
if (cache.has(root)) return cache.get(root);
|
||||||
|
const file = path.join(root, 'instance-id');
|
||||||
|
let id = '';
|
||||||
|
try {
|
||||||
|
id = fs.readFileSync(file, 'utf8').trim();
|
||||||
|
} catch (_) {}
|
||||||
|
if (!/^[0-9a-f]{12}$/.test(id)) {
|
||||||
|
id = crypto.randomBytes(6).toString('hex');
|
||||||
|
try {
|
||||||
|
fs.writeFileSync(file, id + '\n');
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
cache.set(root, id);
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { instanceId };
|
||||||
+92
-8
@@ -3,6 +3,11 @@
|
|||||||
const fs = require('fs');
|
const fs = require('fs');
|
||||||
const path = require('path');
|
const path = require('path');
|
||||||
|
|
||||||
|
// 增量上下文:context_id -> { len }(本进程认为 relay 已存到第几条)。
|
||||||
|
// 只存指针不存正文;进程重启即清空 → 下一轮发全量,relay 整段替换,行为正确。
|
||||||
|
// 不存 hash:id 里已经带 archived_cnt(压缩代数),压缩后 id 自变、缓存自然对不上。
|
||||||
|
const ctxState = new Map();
|
||||||
|
|
||||||
const SYSTEM_PROMPT_TEMPLATE = fs.readFileSync(path.join(__dirname, 'templates', 'profile-default.txt'), 'utf8');
|
const SYSTEM_PROMPT_TEMPLATE = fs.readFileSync(path.join(__dirname, 'templates', 'profile-default.txt'), 'utf8');
|
||||||
|
|
||||||
// 上下文压缩提示词(templates/prompt-compress.txt):点「压缩」时不插入指令消息。
|
// 上下文压缩提示词(templates/prompt-compress.txt):点「压缩」时不插入指令消息。
|
||||||
@@ -308,7 +313,7 @@ function buildMessages(session, language, mintUrl, profile, withProfile, trimOn)
|
|||||||
// summarize_request(旧版遗留行):仅在未收尾的旧压缩回合内发给模型,其余一律跳过
|
// summarize_request(旧版遗留行):仅在未收尾的旧压缩回合内发给模型,其余一律跳过
|
||||||
if (row.type === 'summarize_request') {
|
if (row.type === 'summarize_request') {
|
||||||
if (i > lastClosingAssistant && (row.content || '').trim()) {
|
if (i > lastClosingAssistant && (row.content || '').trim()) {
|
||||||
messages.push({ role: 'user', content: row.content });
|
messages.push({ role: 'user', content: row.content, __rowId: row.id });
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -338,7 +343,7 @@ function buildMessages(session, language, mintUrl, profile, withProfile, trimOn)
|
|||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const m = { role: 'assistant', content: row.content || '' };
|
const m = { role: 'assistant', content: row.content || '', __rowId: row.id };
|
||||||
// 思维链回传原料:存库 reasoning 随原样带给 callModel(中性内部键,按模型
|
// 思维链回传原料:存库 reasoning 随原样带给 callModel(中性内部键,按模型
|
||||||
// reasoning_ack_field 改名注入后此键必被剥除,不会泄往上游)。
|
// reasoning_ack_field 改名注入后此键必被剥除,不会泄往上游)。
|
||||||
if (row.reasoning) m.__reasoning = row.reasoning;
|
if (row.reasoning) m.__reasoning = row.reasoning;
|
||||||
@@ -419,9 +424,9 @@ function buildMessages(session, language, mintUrl, profile, withProfile, trimOn)
|
|||||||
}
|
}
|
||||||
if (row.role === 'tool') {
|
if (row.role === 'tool') {
|
||||||
if (trimActive && typeof content === 'string') content = trimToolContent(content, row, callById, roundsAfter, turnsAfter);
|
if (trimActive && typeof content === 'string') content = trimToolContent(content, row, callById, roundsAfter, turnsAfter);
|
||||||
messages.push({ role: 'tool', tool_call_id: row.tool_call_id, name: row.name, content });
|
messages.push({ role: 'tool', tool_call_id: row.tool_call_id, name: row.name, content, __rowId: row.id });
|
||||||
} else {
|
} else {
|
||||||
messages.push({ role: row.role, content });
|
messages.push({ role: row.role, content, __rowId: row.id });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
// 未消费图片合并发送:图上文字置顶、图块紧随(同序)。
|
// 未消费图片合并发送:图上文字置顶、图块紧随(同序)。
|
||||||
@@ -649,6 +654,14 @@ function splitInlineThinking(raw) {
|
|||||||
return { content: text.trim(), reasoning: think.trim() };
|
return { content: text.trim(), reasoning: think.trim() };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 剥离内部键 __rowId(锚点用):有才拷贝,没就原样返回,避免每行都新建对象
|
||||||
|
function stripRowId(m) {
|
||||||
|
if (!m || m.__rowId == null) return m;
|
||||||
|
const c = Object.assign({}, m);
|
||||||
|
delete c.__rowId;
|
||||||
|
return c;
|
||||||
|
}
|
||||||
|
|
||||||
// 调模型一次。onText(textDelta) 回调流式文本。
|
// 调模型一次。onText(textDelta) 回调流式文本。
|
||||||
// 返回 { content, tool_calls: [{id,name,arguments(string)}], finish_reason, usage, aborted }
|
// 返回 { content, tool_calls: [{id,name,arguments(string)}], finish_reason, usage, aborted }
|
||||||
// 可选回调 opts.onToolCallStart({id,name}):某 tool_call 首次凑齐 id+name 时触发一次;
|
// 可选回调 opts.onToolCallStart({id,name}):某 tool_call 首次凑齐 id+name 时触发一次;
|
||||||
@@ -686,20 +699,23 @@ async function callModel(cfg, modelId, messages, tools, options) {
|
|||||||
// 思维链回传(逐模型 opt-in):开思考时把 buildMessages 挂的内部键 __reasoning 按
|
// 思维链回传(逐模型 opt-in):开思考时把 buildMessages 挂的内部键 __reasoning 按
|
||||||
// reasoning_ack_field 写回 assistant 行;关思考时整段不发。带 tool_calls 的行缺思维链
|
// reasoning_ack_field 写回 assistant 行;关思考时整段不发。带 tool_calls 的行缺思维链
|
||||||
// 时用空串占位(缺失会被上游 400,空串实测通过)。__reasoning 是内部键,任何情况都剥。
|
// 时用空串占位(缺失会被上游 400,空串实测通过)。__reasoning 是内部键,任何情况都剥。
|
||||||
|
// __rowId(锚点用的库行 id)同样是内部键:没想发也不该发给上游,任何行有就剥。
|
||||||
if (body.messages && body.messages.length) {
|
if (body.messages && body.messages.length) {
|
||||||
const ack = modelCfg.reasoning_ack_field;
|
const ack = modelCfg.reasoning_ack_field;
|
||||||
const send = !!(ack && opts.deepThink);
|
const send = !!(ack && opts.deepThink);
|
||||||
body.messages = body.messages.map(mm => {
|
body.messages = body.messages.map(mm => {
|
||||||
if (!mm || mm.role !== 'assistant') return mm;
|
if (!mm || mm.role !== 'assistant') return stripRowId(mm);
|
||||||
if (!mm.__reasoning) {
|
if (!mm.__reasoning) {
|
||||||
if (!send || !mm.tool_calls) return mm;
|
if (!send || !mm.tool_calls) return stripRowId(mm);
|
||||||
const c = Object.assign({}, mm);
|
const c = Object.assign({}, mm);
|
||||||
c[ack] = '';
|
c[ack] = '';
|
||||||
|
delete c.__rowId; // 内部键,不发给上游
|
||||||
return c;
|
return c;
|
||||||
}
|
}
|
||||||
const c = Object.assign({}, mm);
|
const c = Object.assign({}, mm);
|
||||||
if (send) c[ack] = mm.__reasoning;
|
if (send) c[ack] = mm.__reasoning;
|
||||||
delete c.__reasoning;
|
delete c.__reasoning;
|
||||||
|
delete c.__rowId;
|
||||||
return c;
|
return c;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -714,18 +730,78 @@ async function callModel(cfg, modelId, messages, tools, options) {
|
|||||||
opts.onFetchParams(logBody);
|
opts.onFetchParams(logBody);
|
||||||
}
|
}
|
||||||
|
|
||||||
const res = await fetch(modelCfg.url + '/chat/completions', {
|
// ---- 增量上下文(context relay)----
|
||||||
|
// 仅对显式 store: true 的模型生效,且必须带 opts.context_id。
|
||||||
|
// id 尾部的 archived_cnt 就是「压缩代数」:压缩会把老行标 archived,代数一变 id 就变,
|
||||||
|
// relay 自然找不到缓存并回 409,不需要额外传 hash。
|
||||||
|
// 裁剪不改 id(只换内容不删行),所以它不会打断增量:relay 里留着完本文,模型读到的信息更多。
|
||||||
|
//
|
||||||
|
// 能不能只发新增,靠「锚点」判:上一轮发出去的最后一条库行(其 messages.id)还在不在
|
||||||
|
// 本轮数组的同一位置上。历史被改只有两种形态——尾部截断(编辑/清空/压缩后)与中间挖洞
|
||||||
|
//(删单条,由 invalidateContext 另行作废)——前者必然让锚点对不上。
|
||||||
|
// 只比长度是不行的:编辑台丢弃历史后新内容又长出来,长度可能反而更大,切点就错位了,
|
||||||
|
// relay 忠实 concat 出一份错位数组,上游按 tool_call_mismatch 拒收。
|
||||||
|
const cid = opts.context_id;
|
||||||
|
const storeOn = !!(modelCfg.store && cid);
|
||||||
|
const fullBody = JSON.stringify(body);
|
||||||
|
// 已剥内部键的全量数组(上面 map 的产物,保序保长)。增量分支会把它替换成尾部切片,
|
||||||
|
// 所以先存一份:409 重试要拿它重发全量,不能拿原始 messages(那上面挂着 __rowId)。
|
||||||
|
const strippedFull = body.messages;
|
||||||
|
if (storeOn) {
|
||||||
|
const st = ctxState.get(cid);
|
||||||
|
headers['X-Context-Id'] = cid;
|
||||||
|
// 锚点:上一轮发出去的数组里最后一条库行的 messages.id。
|
||||||
|
const anchor = st && st.len > 0 ? messages[st.len - 1] : null;
|
||||||
|
const anchorOk = !!(st && anchor && anchor.__rowId === st.lastRowId);
|
||||||
|
if (anchorOk && messages.length === st.len) {
|
||||||
|
// 数组与上次一模一样(错误重试 / 切模型但没新增消息):发空增量,
|
||||||
|
// relay 用缓存原样转发即可。缓存不在时它会回 409,下面重试一次全量。
|
||||||
|
body.messages = [];
|
||||||
|
} else if (anchorOk && messages.length > st.len) {
|
||||||
|
// 前缀没动:只发新增。strippedFull 与 messages 同序同长,索引可直接沿用。
|
||||||
|
body.messages = strippedFull.slice(st.len);
|
||||||
|
} else {
|
||||||
|
// 全量:首轮 / 进程重启 / 压缩后新 id / 历史被改
|
||||||
|
headers['X-Context-Reset'] = '1';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let res = await fetch(modelCfg.url + '/chat/completions', {
|
||||||
|
method: 'POST',
|
||||||
|
headers,
|
||||||
|
body: storeOn ? JSON.stringify(body) : fullBody,
|
||||||
|
signal: controller.signal,
|
||||||
|
});
|
||||||
|
|
||||||
|
// 409 = relay 那边没有这个 id 的缓存(重启 / TTL / LRU / 压缩换了 id):改发全量重试一次。
|
||||||
|
// 只重试一次:重发的是全量(带 Reset 头),relay 会整段存下,不可能再 409。
|
||||||
|
if (storeOn && res.status === 409) {
|
||||||
|
body.messages = strippedFull; // 已剥内部键的全量,不能拿原始 messages
|
||||||
|
headers['X-Context-Reset'] = '1';
|
||||||
|
res = await fetch(modelCfg.url + '/chat/completions', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers,
|
headers,
|
||||||
body: JSON.stringify(body),
|
body: JSON.stringify(body),
|
||||||
signal: controller.signal,
|
signal: controller.signal,
|
||||||
});
|
});
|
||||||
|
}
|
||||||
|
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
const text = await res.text().catch(() => '');
|
const text = await res.text().catch(() => '');
|
||||||
const err = new Error('上游返回 ' + res.status + ': ' + text.slice(0, 500));
|
const err = new Error('上游返回 ' + res.status + ': ' + text.slice(0, 500));
|
||||||
err.upstream_status = res.status;
|
err.upstream_status = res.status;
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
|
// 成功才更新“relay 已存到几条”:失败下一轮自然重发全量。
|
||||||
|
// lastRowId 取本轮发出去的数组里最后一个「来自数据库的行」的 id(末尾可能是合成的
|
||||||
|
// 图片提示行,没有 __rowId,要往前找):它就是下一轮比对的锚点。
|
||||||
|
if (storeOn) {
|
||||||
|
let lastRowId = null;
|
||||||
|
for (let i = messages.length - 1; i >= 0; i--) {
|
||||||
|
if (messages[i] && messages[i].__rowId != null) { lastRowId = messages[i].__rowId; break; }
|
||||||
|
}
|
||||||
|
ctxState.set(cid, { len: messages.length, lastRowId: lastRowId });
|
||||||
|
}
|
||||||
|
|
||||||
let content = '';
|
let content = '';
|
||||||
let reasoning = '';
|
let reasoning = '';
|
||||||
@@ -815,4 +891,12 @@ async function callModel(cfg, modelId, messages, tools, options) {
|
|||||||
return { content, reasoning, tool_calls: Array.from(toolCalls.values()), finish_reason: finishReason, usage, aborted, sseFrames };
|
return { content, reasoning, tool_calls: Array.from(toolCalls.values()), finish_reason: finishReason, usage, aborted, sseFrames };
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = { callModel, buildMessages, buildSystemPrompt, systemPromptText, setSkillListText, setEnvMode, setPayloadTrim, setProfilePrompts, encodeBlocks, decodeBlocks, compressMessages, titleMessages, patchImageReceipt };
|
// 作废某会话的增量上下文指针:下一轮直接走 X-Context-Reset 全量重建。
|
||||||
|
// 用在「历史被挖了一个洞」的地方——删中间某条消息时,后面的行位置没变、
|
||||||
|
// 锚点(末尾行 id)查不出异常,但 relay 缓存里还留着被删那行,增量拼出来就错位了。
|
||||||
|
// 压缩不用调:压缩会改 cid(archived_cnt +1),自然回落。
|
||||||
|
function invalidateContext(cid) {
|
||||||
|
if (cid) ctxState.delete(cid);
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { callModel, buildMessages, buildSystemPrompt, systemPromptText, setSkillListText, setEnvMode, setPayloadTrim, setProfilePrompts, encodeBlocks, decodeBlocks, compressMessages, titleMessages, patchImageReceipt, invalidateContext };
|
||||||
|
|||||||
+46
-7
@@ -118,7 +118,7 @@ function tokenScore(fl, t) {
|
|||||||
const frac = hit / (t.length - 1);
|
const frac = hit / (t.length - 1);
|
||||||
return frac >= 0.5 ? frac * 0.9 : 0;
|
return frac >= 0.5 ? frac * 0.9 : 0;
|
||||||
}
|
}
|
||||||
function searchFragments(db, user, query, count) {
|
function searchFragments(db, user, query, count, excludeSid) {
|
||||||
const toks = String(query || '').toLowerCase().split(/[\s,,、;;。.!!??]+/).filter(Boolean).slice(0, 8);
|
const toks = String(query || '').toLowerCase().split(/[\s,,、;;。.!!??]+/).filter(Boolean).slice(0, 8);
|
||||||
if (!toks.length) return '';
|
if (!toks.length) return '';
|
||||||
const lim = Math.max(1, Math.min(30, Number(count) || 10));
|
const lim = Math.max(1, Math.min(30, Number(count) || 10));
|
||||||
@@ -132,6 +132,23 @@ function searchFragments(db, user, query, count) {
|
|||||||
for (const t of toks) sum += tokenScore(fl, t);
|
for (const t of toks) sum += tokenScore(fl, t);
|
||||||
if (sum > 0) hits.push({ r: r, score: sum / toks.length, i: i });
|
if (sum > 0) hits.push({ r: r, score: sum / toks.length, i: i });
|
||||||
});
|
});
|
||||||
|
// 未收口的会话没有碎片,标题是它唯一可检索的记忆:同样打分、同样渲染、同样排序,
|
||||||
|
// 不另起段落(否则模型会把「标题命中」当另一类东西,反而不信)。
|
||||||
|
const pend = db.prepare(
|
||||||
|
"SELECT id, title, updated_at FROM sessions WHERE user = ? AND journaled_at IS NULL AND TRIM(title) != ''"
|
||||||
|
).all(String(user || ''));
|
||||||
|
pend.forEach((s, i) => {
|
||||||
|
if (excludeSid && s.id === excludeSid) return;
|
||||||
|
const fl = String(s.title).toLowerCase();
|
||||||
|
let sum = 0;
|
||||||
|
for (const t of toks) sum += tokenScore(fl, t);
|
||||||
|
if (sum > 0) {
|
||||||
|
hits.push({
|
||||||
|
r: { session_id: s.id, day: dayString(s.updated_at), text: s.title, last_active_at: s.updated_at },
|
||||||
|
score: sum / toks.length, i: rows.length + i
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
if (!hits.length) return '';
|
if (!hits.length) return '';
|
||||||
hits.sort((a, b) => b.score - a.score || a.i - b.i);
|
hits.sort((a, b) => b.score - a.score || a.i - b.i);
|
||||||
const shown = hits.slice(0, lim);
|
const shown = hits.slice(0, lim);
|
||||||
@@ -143,14 +160,36 @@ function searchFragments(db, user, query, count) {
|
|||||||
|
|
||||||
// ---------- 读:日期索引 / 某天整天(只记得「大概哪天」时的翻页) ----------
|
// ---------- 读:日期索引 / 某天整天(只记得「大概哪天」时的翻页) ----------
|
||||||
function daysIndex(db, user) {
|
function daysIndex(db, user) {
|
||||||
return db.prepare(
|
const u = String(user || '');
|
||||||
'SELECT day, COUNT(*) n FROM memory_fragments WHERE user = ? GROUP BY day ORDER BY day DESC'
|
const map = new Map();
|
||||||
).all(String(user || '')).map(r => '- ' + r.day + '(' + r.n + ' 条)');
|
for (const r of db.prepare('SELECT day, COUNT(*) n FROM memory_fragments WHERE user = ? GROUP BY day').all(u)) {
|
||||||
|
map.set(r.day, (map.get(r.day) || 0) + r.n);
|
||||||
|
}
|
||||||
|
// 未收口会话的日期也要进索引:那天干过活,只是还没落碎片,索引里不该整天消失。
|
||||||
|
// 日期一律走 dayString(业务时区 Asia/Shanghai),不交给 SQLite 的 localtime,避免容器 TZ 漂移。
|
||||||
|
for (const s of db.prepare(
|
||||||
|
"SELECT updated_at FROM sessions WHERE user = ? AND journaled_at IS NULL AND TRIM(title) != ''"
|
||||||
|
).all(u)) {
|
||||||
|
const d = dayString(s.updated_at);
|
||||||
|
map.set(d, (map.get(d) || 0) + 1);
|
||||||
|
}
|
||||||
|
return [...map.entries()].sort((a, b) => (a[0] < b[0] ? 1 : a[0] > b[0] ? -1 : 0))
|
||||||
|
.map(e => '- ' + e[0] + '(' + e[1] + ' 条)');
|
||||||
}
|
}
|
||||||
function dayEntry(db, user, date) {
|
function dayEntry(db, user, date) {
|
||||||
return db.prepare(
|
const u = String(user || '');
|
||||||
'SELECT ' + FRAG_COLS + FRAG_FROM + ' WHERE f.user = ? AND f.day = ? ORDER BY COALESCE(f.last_active_at, f.created_at)'
|
const d = String(date || '').trim();
|
||||||
).all(String(user || ''), String(date || '').trim()).map(renderFrag).join('\n\n');
|
const rows = db.prepare(
|
||||||
|
'SELECT ' + FRAG_COLS + FRAG_FROM + ' WHERE f.user = ? AND f.day = ?'
|
||||||
|
).all(u, d);
|
||||||
|
for (const s of db.prepare(
|
||||||
|
"SELECT id, title, updated_at FROM sessions WHERE user = ? AND journaled_at IS NULL AND TRIM(title) != ''"
|
||||||
|
).all(u)) {
|
||||||
|
if (dayString(s.updated_at) !== d) continue;
|
||||||
|
rows.push({ session_id: s.id, day: d, text: s.title, last_active_at: s.updated_at });
|
||||||
|
}
|
||||||
|
rows.sort((a, b) => (Number(a.last_active_at) || 0) - (Number(b.last_active_at) || 0));
|
||||||
|
return rows.map(renderFrag).join('\n\n');
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------- 裁剪:day 为 ISO 串,字典序即日期序;默认永久存储为 no-op ----------
|
// ---------- 裁剪:day 为 ISO 串,字典序即日期序;默认永久存储为 no-op ----------
|
||||||
|
|||||||
+11
-3
@@ -95,7 +95,7 @@
|
|||||||
{
|
{
|
||||||
"key": "video_task",
|
"key": "video_task",
|
||||||
"label": "视频生成",
|
"label": "视频生成",
|
||||||
"desc": "智谱 BigModel 异步视频接口",
|
"desc": "文生视频 / 图生视频",
|
||||||
"url": "http://mcp_video_task:3000/mcp",
|
"url": "http://mcp_video_task:3000/mcp",
|
||||||
"mode": "skill",
|
"mode": "skill",
|
||||||
"fields": [
|
"fields": [
|
||||||
@@ -105,12 +105,20 @@
|
|||||||
"secret": true,
|
"secret": true,
|
||||||
"prefix": "Bearer ",
|
"prefix": "Bearer ",
|
||||||
"required": true,
|
"required": true,
|
||||||
"placeholder": "智谱 API Key"
|
"placeholder": "API Key"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"header": "X-Video-Task-Base-Url",
|
||||||
|
"label": "地址",
|
||||||
|
"required": true,
|
||||||
|
"placeholder": "https://<host>/v1",
|
||||||
|
"hint": "OpenAI 兼容 videos / generations"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"header": "X-Video-Task-Model",
|
"header": "X-Video-Task-Model",
|
||||||
"label": "模型",
|
"label": "模型",
|
||||||
"default": "cogvideox-flash"
|
"required": true,
|
||||||
|
"placeholder": "上游的模型 id"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
|
|||||||
+435
-150
File diff suppressed because it is too large
Load Diff
+149
-51
@@ -8,21 +8,38 @@
|
|||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover, interactive-widget=resizes-content">
|
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover, interactive-widget=resizes-content">
|
||||||
<title>Agent 任务台</title>
|
<title>Agent 任务台</title>
|
||||||
<script src="/vendor/marked.min.js"></script>
|
<script src="/vendor/marked.min.js"></script>
|
||||||
|
<script src="/vendor/katex/katex.min.js"></script>
|
||||||
|
<script src="/js/math.js"></script>
|
||||||
|
<script src="/vendor/prism.min.js"></script>
|
||||||
<meta name="theme-color" content="#3964FE">
|
<meta name="theme-color" content="#3964FE">
|
||||||
|
<!-- 主题首屏:先落 data-theme,避开刷新时的白屏闪一下。默认浅色,手动切过后存 localStorage -->
|
||||||
|
<script>
|
||||||
|
(function () {
|
||||||
|
try {
|
||||||
|
var m = localStorage.getItem('agent-theme') === 'dark' ? 'dark' : 'light';
|
||||||
|
document.documentElement.setAttribute('data-theme', m);
|
||||||
|
document.documentElement.setAttribute('data-theme-mode', m);
|
||||||
|
} catch (_) {
|
||||||
|
document.documentElement.setAttribute('data-theme', 'light');
|
||||||
|
document.documentElement.setAttribute('data-theme-mode', 'light');
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
<meta name="apple-mobile-web-app-capable" content="yes">
|
<meta name="apple-mobile-web-app-capable" content="yes">
|
||||||
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
|
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
|
||||||
<meta name="apple-mobile-web-app-title" content="Agent">
|
<meta name="apple-mobile-web-app-title" content="Agent">
|
||||||
<link rel="manifest" href="/manifest.json">
|
<link rel="manifest" href="/manifest.json">
|
||||||
<link rel="apple-touch-icon" href="/icons/apple-touch-icon.png">
|
<link rel="apple-touch-icon" href="/icons/apple-touch-icon.png">
|
||||||
<link rel="icon" type="image/png" sizes="192x192" href="/icons/icon-192.png">
|
<link rel="icon" type="image/png" sizes="192x192" href="/icons/icon-192.png">
|
||||||
|
<link rel="stylesheet" href="/vendor/katex/katex.min.css">
|
||||||
<link rel="stylesheet" href="/css/style.css">
|
<link rel="stylesheet" href="/css/style.css">
|
||||||
<style>
|
<style>
|
||||||
/* 「压缩」摘要卡片:与 .msg-ctx(画像快照/渠道/记忆)同一套视觉——淡蓝底、蓝边蓝字、
|
/* 「压缩」摘要卡片:与 .msg-ctx(画像快照/渠道/记忆)同一套视觉——淡蓝底、蓝边蓝字、
|
||||||
三角箭头、虚线分隔。纯色不用渐变/阴影,折叠与展开同一底色。默认收起 */
|
三角箭头、虚线分隔。纯色不用渐变/阴影,折叠与展开同一底色。默认收起 */
|
||||||
.msg-summary {
|
.msg-summary {
|
||||||
width: 100%; /* .msg.other 是 align-items:flex-start 的列 flex,不写就只撑标题那点宽 */
|
width: 100%; /* .msg.other 是 align-items:flex-start 的列 flex,不写就只撑标题那点宽 */
|
||||||
margin: 0 0 8px; border: 1px solid #dbe4fb; border-radius: 12px; overflow: hidden;
|
margin: 0 0 8px; border: 1px solid var(--bd-dbe4fb); border-radius: 12px; overflow: hidden;
|
||||||
background: #f7f9ff;
|
background: var(--bg-f7f9ff);
|
||||||
}
|
}
|
||||||
.msg-summary > summary {
|
.msg-summary > summary {
|
||||||
list-style: none; cursor: pointer; user-select: none;
|
list-style: none; cursor: pointer; user-select: none;
|
||||||
@@ -37,8 +54,8 @@
|
|||||||
}
|
}
|
||||||
.msg-summary[open] > summary::before { transform: rotate(90deg); }
|
.msg-summary[open] > summary::before { transform: rotate(90deg); }
|
||||||
.msg-summary-body {
|
.msg-summary-body {
|
||||||
/* 比标题区(#f7f9ff)再淡一档,分隔开又不跳色 */
|
/* 比标题区深一档(用变量,暗色自动跟随) */
|
||||||
border-top: 1px dashed #dbe4fb; background: #fbfcff;
|
border-top: 1px dashed var(--bd-dbe4fb); background: var(--bg-fbfcff);
|
||||||
padding: 10px 13px 12px;
|
padding: 10px 13px 12px;
|
||||||
}
|
}
|
||||||
.msg-summary-body .bubble-ai { margin: 0; background: transparent; font-size: 14px; line-height: 1.7; }
|
.msg-summary-body .bubble-ai { margin: 0; background: transparent; font-size: 14px; line-height: 1.7; }
|
||||||
@@ -55,7 +72,7 @@
|
|||||||
#schedule-modal .sched-row select,
|
#schedule-modal .sched-row select,
|
||||||
#schedule-modal .sched-row input {
|
#schedule-modal .sched-row input {
|
||||||
width: auto; margin: 0; padding: 7px 8px; font-size: 14px;
|
width: auto; margin: 0; padding: 7px 8px; font-size: 14px;
|
||||||
border: 1px solid #dde1ea; border-radius: 8px; background: #fff; color: var(--ink);
|
border: 1px solid var(--bd-dde1ea); border-radius: 8px; background: var(--bg-fff); color: var(--ink);
|
||||||
}
|
}
|
||||||
#schedule-modal .sched-row select { appearance: none; -webkit-appearance: none; }
|
#schedule-modal .sched-row select { appearance: none; -webkit-appearance: none; }
|
||||||
#schedule-modal .sched-row .sched-num { width: 52px; text-align: center; }
|
#schedule-modal .sched-row .sched-num { width: 52px; text-align: center; }
|
||||||
@@ -64,9 +81,9 @@
|
|||||||
/* schedule 弹窗内的提示词编辑区(.modal input 不覆盖 textarea,单独给样式) */
|
/* schedule 弹窗内的提示词编辑区(.modal input 不覆盖 textarea,单独给样式) */
|
||||||
#schedule-modal textarea {
|
#schedule-modal textarea {
|
||||||
width: 100%; box-sizing: border-box; display: block;
|
width: 100%; box-sizing: border-box; display: block;
|
||||||
border: 1px solid #dde1ea; border-radius: 10px;
|
border: 1px solid var(--bd-dde1ea); border-radius: 10px;
|
||||||
padding: 10px 12px; font-size: 14px; line-height: 1.5;
|
padding: 10px 12px; font-size: 14px; line-height: 1.5;
|
||||||
margin-bottom: 10px; background: #fff; color: var(--ink); resize: vertical;
|
margin-bottom: 10px; background: var(--bg-fff); color: var(--ink); resize: vertical;
|
||||||
}
|
}
|
||||||
#schedule-modal textarea:focus { border-color: var(--active); }
|
#schedule-modal textarea:focus { border-color: var(--active); }
|
||||||
/* welcome 头像兼做「选择模型」入口(与聊天态的「选择模型」同一弹窗) */
|
/* welcome 头像兼做「选择模型」入口(与聊天态的「选择模型」同一弹窗) */
|
||||||
@@ -84,12 +101,79 @@
|
|||||||
</script>
|
</script>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
|
<!-- 图标 sprite:全站 99 处 svg 的几何图形都收在这里,引用方式
|
||||||
|
<svg class="ic" viewBox="0 0 24 24"><use href="#i-xxx"/></svg>
|
||||||
|
尺寸/描边仍由各处 CSS 控制(.ic、.tree-act svg 等),本文件只存形状。
|
||||||
|
同形但历史写法不同的(folder/folder-b/folder-c、x-line/x-line-b/x-path、eye/eye-sm 等)
|
||||||
|
各留一份,保证替换前后逐像素一致;后续要收敛,改引用指向同一个 id 即可。 -->
|
||||||
|
<svg id="icon-sprite" style="position:absolute;width:0;height:0;overflow:hidden" aria-hidden="true">
|
||||||
|
<symbol id="i-history" viewBox="0 0 24 24"><path stroke-width="2" stroke-linecap="round" d="M4 5h16M4 15h10"/></symbol>
|
||||||
|
<symbol id="i-clock" viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.5"></circle><polyline points="12 7.5 12 12 15.5 14"></polyline></symbol>
|
||||||
|
<symbol id="i-database" viewBox="0 0 24 24"><ellipse cx="12" cy="5" rx="8" ry="2.5" fill="none" stroke="currentColor" stroke-width="1.6"></ellipse><path fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" d="M4 5v6c0 1.4 3.6 2.5 8 2.5s8-1.1 8-2.5V5"></path><path fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" d="M4 11v6c0 1.4 3.6 2.5 8 2.5s8-1.1 8-2.5v-6"></path></symbol>
|
||||||
|
<symbol id="i-plus" viewBox="0 0 24 24"><line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line></symbol>
|
||||||
|
<symbol id="i-more" viewBox="0 0 24 24"><circle cx="5" cy="12" r="1.4" fill="currentColor" stroke="none"></circle><circle cx="12" cy="12" r="1.4" fill="currentColor" stroke="none"></circle><circle cx="19" cy="12" r="1.4" fill="currentColor" stroke="none"></circle></symbol>
|
||||||
|
<symbol id="i-sliders" viewBox="0 0 24 24"><line x1="3" y1="7" x2="21" y2="7"></line><circle cx="9" cy="7" r="2.6"></circle><line x1="3" y1="17" x2="21" y2="17"></line><circle cx="15" cy="17" r="2.6"></circle></symbol>
|
||||||
|
<symbol id="i-robot" viewBox="0 0 24 24"><rect x="4" y="8" width="16" height="12" rx="3"></rect><line x1="12" y1="4" x2="12" y2="8"></line><circle cx="12" cy="3" r="1.4"></circle><circle cx="9" cy="13.5" r="1" fill="currentColor" stroke="none"></circle><circle cx="15" cy="13.5" r="1" fill="currentColor" stroke="none"></circle><line x1="9.5" y1="17" x2="14.5" y2="17"></line></symbol>
|
||||||
|
<symbol id="i-folder" viewBox="0 0 24 24"><path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path></symbol>
|
||||||
|
<symbol id="i-x-line" viewBox="0 0 24 24"><line x1="6" y1="6" x2="18" y2="18"></line><line x1="18" y1="6" x2="6" y2="18"></line></symbol>
|
||||||
|
<symbol id="i-bulb" viewBox="0 0 24 24"><path d="M12 10.2a1.8 1.8 0 1 0 0.001 3.6A1.8 1.8 0 0 0 12 10.2z"></path><path stroke-width="1.5" d="M15.76 15.76 C10.955 20.565 5.373 22.779 3.297 20.703 C1.22 18.627 3.434 13.045 8.24 8.24 C13.045 3.435 18.627 1.22 20.703 3.297 C22.779 5.374 20.565 10.955 15.76 15.76z"></path><path stroke-width="1.5" d="M16.096 7.904 C20.905 12.713 22.965 18.298 20.703 20.703 C18.44 23.108 13.003 20.755 8.24 15.76 C3.477 10.76 1.22 5.373 3.297 3.297 C5.374 1.22 10.955 3.434 16.096 7.904z"></path></symbol>
|
||||||
|
<symbol id="i-folder-b" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"></path></symbol>
|
||||||
|
<symbol id="i-paperclip" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"></path></symbol>
|
||||||
|
<symbol id="i-send" viewBox="0 0 24 24"><line x1="12" y1="19" x2="12" y2="5"></line><polyline points="5 12 12 5 19 12"></polyline></symbol>
|
||||||
|
<symbol id="i-mic" viewBox="0 0 24 24"><rect x="9" y="2" width="6" height="12" rx="3"></rect><path d="M5 10a7 7 0 0 0 14 0"></path><line x1="12" y1="19" x2="12" y2="22"></line></symbol>
|
||||||
|
<symbol id="i-keyboard" viewBox="0 0 24 24"><rect x="3" y="5" width="18" height="14" rx="2.5"></rect><circle cx="7" cy="9" r="1.1" fill="currentColor" stroke="none"></circle><circle cx="12" cy="9" r="1.1" fill="currentColor" stroke="none"></circle><circle cx="17" cy="9" r="1.1" fill="currentColor" stroke="none"></circle><circle cx="7" cy="12.5" r="1.1" fill="currentColor" stroke="none"></circle><circle cx="12" cy="12.5" r="1.1" fill="currentColor" stroke="none"></circle><circle cx="17" cy="12.5" r="1.1" fill="currentColor" stroke="none"></circle><line x1="8" y1="16" x2="16" y2="16"></line></symbol>
|
||||||
|
<symbol id="i-chevron-down" viewBox="0 0 24 24"><polyline points="6 9 12 15 18 9"></polyline></symbol>
|
||||||
|
<symbol id="i-spinner" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10" style="fill:none;stroke:var(--sb-ring,#dde);stroke-width:2.5"></circle><path d="M22 12a10 10 0 0 1-10 10" style="fill:none;stroke:var(--sb-arc,#3964FE);stroke-width:2.5;stroke-linecap:round"></path></symbol>
|
||||||
|
<symbol id="i-search" viewBox="0 0 24 24"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></symbol>
|
||||||
|
<symbol id="i-gear" viewBox="0 0 24 24"><circle cx="12" cy="12" r="3"></circle><path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"></path></symbol>
|
||||||
|
<symbol id="i-upload-cloud" viewBox="0 0 24 24"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="17 8 12 3 7 8"></polyline><line x1="12" y1="3" x2="12" y2="15"></line></symbol>
|
||||||
|
<symbol id="i-download" viewBox="0 0 24 24"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="7 10 12 15 17 10"></polyline><line x1="12" y1="15" x2="12" y2="3"></line></symbol>
|
||||||
|
<symbol id="i-trash" viewBox="0 0 24 24"><path d="M3 6h18"/><path d="M8 6V4a1 1 0 0 1 1-1h6a1 1 0 0 1 1 1v2"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M10 11v6"/><path d="M14 11v6"/></symbol>
|
||||||
|
<symbol id="i-chevron-left" viewBox="0 0 24 24"><polyline points="15 18 9 12 15 6"></polyline></symbol>
|
||||||
|
<symbol id="i-x-line-b" viewBox="0 0 24 24"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></symbol>
|
||||||
|
<symbol id="i-refresh" viewBox="0 0 24 24"><polyline points="23 4 23 10 17 10"></polyline><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"></path></symbol>
|
||||||
|
<symbol id="i-external" viewBox="0 0 24 24"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"></path><polyline points="15 3 21 3 21 9"></polyline><line x1="10" y1="14" x2="21" y2="3"></line></symbol>
|
||||||
|
<symbol id="i-eye" viewBox="0 0 24 24"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path><circle cx="12" cy="12" r="3"></circle></symbol>
|
||||||
|
<symbol id="i-maximize" viewBox="0 0 24 24"><path d="M8 3H5a2 2 0 0 0-2 2v3"></path><path d="M21 8V5a2 2 0 0 0-2-2h-3"></path><path d="M16 21h3a2 2 0 0 0 2-2v-3"></path><path d="M3 16v3a2 2 0 0 0 2 2h3"></path></symbol>
|
||||||
|
<symbol id="i-minimize" viewBox="0 0 24 24"><path d="M8 3v3a2 2 0 0 1-2 2H3"></path><path d="M21 8h-3a2 2 0 0 1-2-2V3"></path><path d="M3 16h3a2 2 0 0 1 2 2v3"></path><path d="M16 21v-3a2 2 0 0 1 2-2h3"></path></symbol>
|
||||||
|
<symbol id="i-copy" viewBox="0 0 24 24"><rect x="9" y="9" width="13" height="13" rx="2"></rect><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path></symbol>
|
||||||
|
<symbol id="i-x-path" viewBox="0 0 24 24"><path d="M18 6 6 18"></path><path d="m6 6 12 12"></path></symbol>
|
||||||
|
<symbol id="i-pencil" viewBox="0 0 24 24"><path d="M12 20h9"></path><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4z"></path></symbol>
|
||||||
|
<symbol id="i-gem" viewBox="0 0 24 24"><path d="M6 3h12l4 6-10 13L2 9z"></path><polyline points="2 9 22 9"></polyline><polyline points="10 3 8 9 12 22"></polyline><polyline points="14 3 16 9 12 22"></polyline></symbol>
|
||||||
|
<symbol id="i-image" viewBox="0 0 24 24"><rect x="3" y="3" width="18" height="18" rx="2"></rect><circle cx="8.5" cy="8.5" r="1.5"></circle><polyline points="21 15 16 10 5 21"></polyline></symbol>
|
||||||
|
<symbol id="i-file" viewBox="0 0 24 24"><path d="M6 3h8l4 4v14H6z"/><path d="M14 3v4h4"/></symbol>
|
||||||
|
<symbol id="i-link" viewBox="0 0 24 24"><path d="M10 13a5 5 0 0 0 7 0l2-2a5 5 0 0 0-7-7l-1 1"/><path d="M14 11a5 5 0 0 0-7 0l-2 2a5 5 0 0 0 7 7l1-1"/></symbol>
|
||||||
|
<symbol id="i-external-b" viewBox="0 0 24 24"><path d="M14 4h6v6"/><path d="M20 4l-9 9"/><path d="M19 14v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1h5"/></symbol>
|
||||||
|
<symbol id="i-reload" viewBox="0 0 24 24"><path d="M20 12a8 8 0 1 1-2.3-5.7"/><path d="M20 4v5h-5"/></symbol>
|
||||||
|
<symbol id="i-terminal" viewBox="0 0 24 24"><rect x="3" y="4" width="18" height="16" rx="2"/><path d="M7 9l3 3-3 3"/><path d="M13 15h4"/></symbol>
|
||||||
|
<symbol id="i-git" viewBox="0 0 24 24"><circle cx="6" cy="5" r="2"/><circle cx="6" cy="19" r="2"/><circle cx="18" cy="7" r="2"/><path d="M6 7v10"/><path d="M18 9v1a4 4 0 0 1-4 4H9"/></symbol>
|
||||||
|
<symbol id="i-eye-sm" viewBox="0 0 24 24"><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12z"/><circle cx="12" cy="12" r="2.6"/></symbol>
|
||||||
|
<symbol id="i-theme-auto" viewBox="0 0 24 24"><rect x="2" y="3" width="20" height="14" rx="2"/><path d="M8 21h8"/><path d="M12 17v4"/></symbol>
|
||||||
|
<symbol id="i-theme-light" viewBox="0 0 24 24"><circle cx="12" cy="12" r="4.5"/><path d="M12 1.5v2M12 20.5v2M3.4 3.4l1.4 1.4M19.2 19.2l1.4 1.4M1.5 12h2M20.5 12h2M3.4 20.6l1.4-1.4M19.2 4.8l1.4-1.4"/></symbol>
|
||||||
|
<symbol id="i-theme-dark" viewBox="0 0 24 24"><path d="M21 13.2A9 9 0 1 1 10.8 3a7.2 7.2 0 0 0 10.2 10.2z"/></symbol>
|
||||||
|
<symbol id="i-file-doc" viewBox="0 0 24 24"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><polyline points="14 2 14 8 20 8"></polyline></symbol>
|
||||||
|
<symbol id="i-folder-c" viewBox="0 0 24 24"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"></path></symbol>
|
||||||
|
<symbol id="i-chevron-right" viewBox="0 0 24 24"><polyline points="9 18 15 12 9 6"></polyline></symbol>
|
||||||
|
<symbol id="i-home" viewBox="0 0 24 24"><path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path><polyline points="9 22 9 12 15 12 15 22"></polyline></symbol>
|
||||||
|
<symbol id="i-image-b" viewBox="0 0 24 24"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect><circle cx="8.5" cy="8.5" r="1.5"></circle><polyline points="21 15 16 10 5 21"></polyline></symbol>
|
||||||
|
<symbol id="i-user" viewBox="0 0 24 24"><circle cx="12" cy="8" r="4"></circle><path d="M4 21c0-4 4-6 8-6s8 2 8 6"></path></symbol>
|
||||||
|
<symbol id="i-users" viewBox="0 0 24 24"><circle cx="9" cy="8" r="3.5"></circle><path d="M2 21c0-3.6 3.1-5.5 7-5.5s7 1.9 7 5.5"></path><path d="M16 8.5a3 3 0 0 1 0 6"></path><path d="M18 21c0-2.8-1.4-4.5-4-5.2"></path></symbol>
|
||||||
|
<symbol id="i-sliders-v" viewBox="0 0 24 24"><line x1="4" y1="21" x2="4" y2="14"></line><line x1="4" y1="10" x2="4" y2="3"></line><line x1="12" y1="21" x2="12" y2="12"></line><line x1="12" y1="8" x2="12" y2="3"></line><line x1="20" y1="21" x2="20" y2="16"></line><line x1="20" y1="12" x2="20" y2="3"></line><line x1="1" y1="14" x2="7" y2="14"></line><line x1="9" y1="8" x2="15" y2="8"></line><line x1="17" y1="16" x2="23" y2="16"></line></symbol>
|
||||||
|
<symbol id="i-zap" viewBox="0 0 24 24"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"></polygon></symbol>
|
||||||
|
<symbol id="i-cpu" viewBox="0 0 24 24"><rect x="4" y="4" width="16" height="16" rx="2"></rect><rect x="9" y="9" width="6" height="6"></rect><line x1="9" y1="1" x2="9" y2="4"></line><line x1="15" y1="1" x2="15" y2="4"></line><line x1="9" y1="20" x2="9" y2="23"></line><line x1="15" y1="20" x2="15" y2="23"></line><line x1="20" y1="9" x2="23" y2="9"></line><line x1="20" y1="14" x2="23" y2="14"></line><line x1="1" y1="9" x2="4" y2="9"></line><line x1="1" y1="14" x2="4" y2="14"></line></symbol>
|
||||||
|
<symbol id="i-layout" viewBox="0 0 24 24"><rect x="3" y="4" width="18" height="16" rx="2"></rect><line x1="3" y1="10" x2="21" y2="10"></line><circle cx="7" cy="15" r="1.2" fill="currentColor" stroke="none"></circle><circle cx="12" cy="15" r="1.2" fill="currentColor" stroke="none"></circle><circle cx="17" cy="15" r="1.2" fill="currentColor" stroke="none"></circle></symbol>
|
||||||
|
<symbol id="i-chevron-right-b" viewBox="0 0 24 24"><polyline points="9 6 15 12 9 18"></polyline></symbol>
|
||||||
|
<symbol id="i-edit" viewBox="0 0 24 24"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path><path d="M18.5 2.5a2.12 2.12 0 0 1 3 3L12 15l-4 1 1-4z"></path></symbol>
|
||||||
|
<symbol id="i-check" viewBox="0 0 24 24"><polyline points="20 6 9 17 4 12"></polyline></symbol>
|
||||||
|
<symbol id="i-pencil-b" viewBox="0 0 24 24"><path d="M12 20h9"/><path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z"/></symbol>
|
||||||
|
</svg>
|
||||||
|
|
||||||
<div id="app">
|
<div id="app">
|
||||||
|
|
||||||
<!-- ================= 顶部导航栏 ================= -->
|
<!-- ================= 顶部导航栏 ================= -->
|
||||||
<header class="header" id="chat-header">
|
<header class="header" id="chat-header">
|
||||||
<button class="icon-btn" id="menu-btn" title="历史记录" aria-label="打开历史记录">
|
<button class="icon-btn" id="menu-btn" title="历史记录" aria-label="打开历史记录">
|
||||||
<svg viewBox="0 0 24 24" class="ic sm"><path stroke-width="2" stroke-linecap="round" d="M4 5h16M4 15h10"/></svg>
|
<svg viewBox="0 0 24 24" class="ic sm"><use href="#i-history"/></svg>
|
||||||
</button>
|
</button>
|
||||||
<div class="header-center" id="header-center"><!-- 未对话状态为空白,JS 注入对话信息 --></div>
|
<div class="header-center" id="header-center"><!-- 未对话状态为空白,JS 注入对话信息 --></div>
|
||||||
|
|
||||||
@@ -100,11 +184,11 @@
|
|||||||
<span class="hdr-label" id="hdr-model-text">选择模型</span>
|
<span class="hdr-label" id="hdr-model-text">选择模型</span>
|
||||||
</button>
|
</button>
|
||||||
<button class="hdr-chip hdr-sched hidden" id="hdr-sched" data-act="schedule" data-tip="定时任务" aria-label="定时任务">
|
<button class="hdr-chip hdr-sched hidden" id="hdr-sched" data-act="schedule" data-tip="定时任务" aria-label="定时任务">
|
||||||
<svg class="ic" viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.5"></circle><polyline points="12 7.5 12 12 15.5 14"></polyline></svg>
|
<svg class="ic" viewBox="0 0 24 24"><use href="#i-clock"/></svg>
|
||||||
<span class="hdr-label" id="hdr-sched-text">定时任务</span>
|
<span class="hdr-label" id="hdr-sched-text">定时任务</span>
|
||||||
</button>
|
</button>
|
||||||
<button class="icon-btn ha-btn hdr-compact hidden" id="hdr-compact" data-act="compact" data-tip="压缩上下文" aria-label="压缩上下文">
|
<button class="icon-btn ha-btn hdr-compact hidden" id="hdr-compact" data-act="compact" data-tip="压缩上下文" aria-label="压缩上下文">
|
||||||
<svg class="ic" viewBox="0 0 24 24"><ellipse cx="12" cy="5" rx="8" ry="2.5" fill="none" stroke="currentColor" stroke-width="1.6"></ellipse><path fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" d="M4 5v6c0 1.4 3.6 2.5 8 2.5s8-1.1 8-2.5V5"></path><path fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" d="M4 11v6c0 1.4 3.6 2.5 8 2.5s8-1.1 8-2.5v-6"></path></svg>
|
<svg class="ic" viewBox="0 0 24 24"><use href="#i-database"/></svg>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -112,28 +196,37 @@
|
|||||||
桌面属性区与菜单项共用 data-act,事件统一在 sessions.js 分发。 -->
|
桌面属性区与菜单项共用 data-act,事件统一在 sessions.js 分发。 -->
|
||||||
<div class="header-actions" id="header-actions">
|
<div class="header-actions" id="header-actions">
|
||||||
<div class="ha-icons">
|
<div class="ha-icons">
|
||||||
|
<button class="icon-btn ha-btn" data-act="theme" id="theme-toggle" data-tip="主题:浅色" aria-label="切换主题">
|
||||||
|
<svg class="ic sm" viewBox="0 0 24 24"><use href="#i-theme-light"/></svg>
|
||||||
|
<svg class="ic sm hidden" viewBox="0 0 24 24"><use href="#i-theme-dark"/></svg>
|
||||||
|
</button>
|
||||||
<button class="icon-btn ha-btn" data-act="new" data-tip="新建会话" aria-label="新建会话">
|
<button class="icon-btn ha-btn" data-act="new" data-tip="新建会话" aria-label="新建会话">
|
||||||
<svg class="ic sm" viewBox="0 0 24 24"><line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line></svg>
|
<svg class="ic sm" viewBox="0 0 24 24"><use href="#i-plus"/></svg>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<button class="icon-btn ha-more" id="ha-more" title="更多" aria-label="更多操作" aria-haspopup="menu" aria-expanded="false" aria-controls="ha-menu">
|
<button class="icon-btn ha-more" id="ha-more" title="更多" aria-label="更多操作" aria-haspopup="menu" aria-expanded="false" aria-controls="ha-menu">
|
||||||
<svg class="ic sm" viewBox="0 0 24 24"><circle cx="5" cy="12" r="1.4" fill="currentColor" stroke="none"></circle><circle cx="12" cy="12" r="1.4" fill="currentColor" stroke="none"></circle><circle cx="19" cy="12" r="1.4" fill="currentColor" stroke="none"></circle></svg>
|
<svg class="ic sm" viewBox="0 0 24 24"><use href="#i-more"/></svg>
|
||||||
</button>
|
</button>
|
||||||
<div class="ha-menu hidden" id="ha-menu" role="menu">
|
<div class="ha-menu hidden" id="ha-menu" role="menu">
|
||||||
<button class="ha-item" role="menuitem" data-act="model">
|
<button class="ha-item" role="menuitem" data-act="model">
|
||||||
<svg class="ic sm" viewBox="0 0 24 24"><line x1="3" y1="7" x2="21" y2="7"></line><circle cx="9" cy="7" r="2.6"></circle><line x1="3" y1="17" x2="21" y2="17"></line><circle cx="15" cy="17" r="2.6"></circle></svg>
|
<svg class="ic sm" viewBox="0 0 24 24"><use href="#i-sliders"/></svg>
|
||||||
<span class="ha-item-main">切换模型</span><span class="ha-item-sub hidden" id="ha-model-sub"></span>
|
<span class="ha-item-main">切换模型</span><span class="ha-item-sub hidden" id="ha-model-sub"></span>
|
||||||
</button>
|
</button>
|
||||||
<button class="ha-item" role="menuitem" data-act="schedule">
|
<button class="ha-item" role="menuitem" data-act="schedule">
|
||||||
<svg class="ic sm" viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.5"></circle><polyline points="12 7.5 12 12 15.5 14"></polyline></svg>
|
<svg class="ic sm" viewBox="0 0 24 24"><use href="#i-clock"/></svg>
|
||||||
<span class="ha-item-main">定时任务</span><span class="ha-item-sub hidden" id="ha-sched-sub"></span>
|
<span class="ha-item-main">定时任务</span><span class="ha-item-sub hidden" id="ha-sched-sub"></span>
|
||||||
</button>
|
</button>
|
||||||
<button class="ha-item" role="menuitem" data-act="compact">
|
<button class="ha-item" role="menuitem" data-act="compact">
|
||||||
<svg class="ic sm" viewBox="0 0 24 24"><ellipse cx="12" cy="5" rx="8" ry="2.5" fill="none" stroke="currentColor" stroke-width="1.6"></ellipse><path fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" d="M4 5v6c0 1.4 3.6 2.5 8 2.5s8-1.1 8-2.5V5"></path><path fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" d="M4 11v6c0 1.4 3.6 2.5 8 2.5s8-1.1 8-2.5v-6"></path></svg>
|
<svg class="ic sm" viewBox="0 0 24 24"><use href="#i-database"/></svg>
|
||||||
<span class="ha-item-main">压缩上下文</span>
|
<span class="ha-item-main">压缩上下文</span>
|
||||||
</button>
|
</button>
|
||||||
|
<button class="ha-item" role="menuitem" data-act="theme" id="theme-toggle-mobile">
|
||||||
|
<svg class="ic sm" viewBox="0 0 24 24"><use href="#i-theme-light"/></svg>
|
||||||
|
<svg class="ic sm hidden" viewBox="0 0 24 24"><use href="#i-theme-dark"/></svg>
|
||||||
|
<span class="ha-item-main">切换主题</span><span class="ha-item-sub" id="theme-label-mobile">浅色</span>
|
||||||
|
</button>
|
||||||
<button class="ha-item" role="menuitem" data-act="new">
|
<button class="ha-item" role="menuitem" data-act="new">
|
||||||
<svg class="ic sm" viewBox="0 0 24 24"><line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line></svg>
|
<svg class="ic sm" viewBox="0 0 24 24"><use href="#i-plus"/></svg>
|
||||||
<span class="ha-item-main">新建会话</span>
|
<span class="ha-item-main">新建会话</span>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
@@ -145,7 +238,7 @@
|
|||||||
<section id="welcome-view">
|
<section id="welcome-view">
|
||||||
<div class="welcome-head">
|
<div class="welcome-head">
|
||||||
<div class="logo-badge" onclick="openModelSwitch()" title="选择模型" role="button" aria-label="选择模型">
|
<div class="logo-badge" onclick="openModelSwitch()" title="选择模型" role="button" aria-label="选择模型">
|
||||||
<svg class="ic" viewBox="0 0 24 24"><rect x="4" y="8" width="16" height="12" rx="3"></rect><line x1="12" y1="4" x2="12" y2="8"></line><circle cx="12" cy="3" r="1.4"></circle><circle cx="9" cy="13.5" r="1" fill="currentColor" stroke="none"></circle><circle cx="15" cy="13.5" r="1" fill="currentColor" stroke="none"></circle><line x1="9.5" y1="17" x2="14.5" y2="17"></line></svg>
|
<svg class="ic" viewBox="0 0 24 24"><use href="#i-robot"/></svg>
|
||||||
</div>
|
</div>
|
||||||
<div class="welcome-slogan">随时开始吧</div>
|
<div class="welcome-slogan">随时开始吧</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -154,11 +247,11 @@
|
|||||||
<div class="welcome-dir hidden" id="welcome-dir">
|
<div class="welcome-dir hidden" id="welcome-dir">
|
||||||
<span class="welcome-dir-cap">工作目录</span>
|
<span class="welcome-dir-cap">工作目录</span>
|
||||||
<button type="button" class="welcome-dir-pick" id="welcome-dir-pick" title="选择本会话的工作目录">
|
<button type="button" class="welcome-dir-pick" id="welcome-dir-pick" title="选择本会话的工作目录">
|
||||||
<svg class="ic sm" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path></svg>
|
<svg class="ic sm" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><use href="#i-folder"/></svg>
|
||||||
<span class="welcome-dir-path" id="welcome-dir-path">默认</span>
|
<span class="welcome-dir-path" id="welcome-dir-path">默认</span>
|
||||||
</button>
|
</button>
|
||||||
<button type="button" class="welcome-dir-clear hidden" id="welcome-dir-clear" title="恢复默认目录" aria-label="恢复默认目录">
|
<button type="button" class="welcome-dir-clear hidden" id="welcome-dir-clear" title="恢复默认目录" aria-label="恢复默认目录">
|
||||||
<svg class="ic sm" viewBox="0 0 24 24"><line x1="6" y1="6" x2="18" y2="18"></line><line x1="18" y1="6" x2="6" y2="18"></line></svg>
|
<svg class="ic sm" viewBox="0 0 24 24"><use href="#i-x-line"/></svg>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
@@ -186,23 +279,23 @@
|
|||||||
<div class="input-actions">
|
<div class="input-actions">
|
||||||
<div class="ia-side ia-left">
|
<div class="ia-side ia-left">
|
||||||
<button class="think-toggle" id="deep-think-btn" title="深度思考">
|
<button class="think-toggle" id="deep-think-btn" title="深度思考">
|
||||||
<svg viewBox="0 0 24 24" class="ic sm"><path d="M12 10.2a1.8 1.8 0 1 0 0.001 3.6A1.8 1.8 0 0 0 12 10.2z"></path><path stroke-width="1.5" d="M15.76 15.76 C10.955 20.565 5.373 22.779 3.297 20.703 C1.22 18.627 3.434 13.045 8.24 8.24 C13.045 3.435 18.627 1.22 20.703 3.297 C22.779 5.374 20.565 10.955 15.76 15.76z"></path><path stroke-width="1.5" d="M16.096 7.904 C20.905 12.713 22.965 18.298 20.703 20.703 C18.44 23.108 13.003 20.755 8.24 15.76 C3.477 10.76 1.22 5.373 3.297 3.297 C5.374 1.22 10.955 3.434 16.096 7.904z"></path></svg>
|
<svg viewBox="0 0 24 24" class="ic sm"><use href="#i-bulb"/></svg>
|
||||||
深度思考
|
深度思考
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<div class="ia-side ia-right">
|
<div class="ia-side ia-right">
|
||||||
<button class="plus-btn" id="files-btn" title="任务文件" aria-label="任务文件">
|
<button class="plus-btn" id="files-btn" title="任务文件" aria-label="任务文件">
|
||||||
<svg viewBox="0 0 24 24" class="ic sm"><path fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"></path></svg>
|
<svg viewBox="0 0 24 24" class="ic sm"><use href="#i-folder-b"/></svg>
|
||||||
</button>
|
</button>
|
||||||
<button class="plus-btn" id="attach-btn" title="上传文件" aria-label="上传文件">
|
<button class="plus-btn" id="attach-btn" title="上传文件" aria-label="上传文件">
|
||||||
<svg viewBox="0 0 24 24" class="ic sm"><path fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"></path></svg>
|
<svg viewBox="0 0 24 24" class="ic sm"><use href="#i-paperclip"/></svg>
|
||||||
</button>
|
</button>
|
||||||
<!-- 同一按钮四态:发送(↑)/ 停止(方块)/ 语音(麦克风)/ 键盘。
|
<!-- 同一按钮四态:发送(↑)/ 停止(方块)/ 语音(麦克风)/ 键盘。
|
||||||
data-state 由 JS 切换,尺寸不变避免输入区跳动 -->
|
data-state 由 JS 切换,尺寸不变避免输入区跳动 -->
|
||||||
<button class="send-btn" id="send-btn" data-state="send" title="发送" aria-label="发送">
|
<button class="send-btn" id="send-btn" data-state="send" title="发送" aria-label="发送">
|
||||||
<svg class="ic sm ic-send" viewBox="0 0 24 24"><line x1="12" y1="19" x2="12" y2="5"></line><polyline points="5 12 12 5 19 12"></polyline></svg>
|
<svg class="ic sm ic-send" viewBox="0 0 24 24"><use href="#i-send"/></svg>
|
||||||
<svg class="ic sm ic-voice" viewBox="0 0 24 24"><rect x="9" y="2" width="6" height="12" rx="3"></rect><path d="M5 10a7 7 0 0 0 14 0"></path><line x1="12" y1="19" x2="12" y2="22"></line></svg>
|
<svg class="ic sm ic-voice" viewBox="0 0 24 24"><use href="#i-mic"/></svg>
|
||||||
<svg class="ic sm ic-kb" viewBox="0 0 24 24"><rect x="3" y="5" width="18" height="14" rx="2.5"></rect><circle cx="7" cy="9" r="1.1" fill="currentColor" stroke="none"></circle><circle cx="12" cy="9" r="1.1" fill="currentColor" stroke="none"></circle><circle cx="17" cy="9" r="1.1" fill="currentColor" stroke="none"></circle><circle cx="7" cy="12.5" r="1.1" fill="currentColor" stroke="none"></circle><circle cx="12" cy="12.5" r="1.1" fill="currentColor" stroke="none"></circle><circle cx="17" cy="12.5" r="1.1" fill="currentColor" stroke="none"></circle><line x1="8" y1="16" x2="16" y2="16"></line></svg>
|
<svg class="ic sm ic-kb" viewBox="0 0 24 24"><use href="#i-keyboard"/></svg>
|
||||||
<span class="stop-sq" aria-hidden="true"></span>
|
<span class="stop-sq" aria-hidden="true"></span>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
@@ -212,13 +305,18 @@
|
|||||||
<div id="voice-overlay" class="hidden" aria-hidden="true">
|
<div id="voice-overlay" class="hidden" aria-hidden="true">
|
||||||
<div class="vo-hint" id="voice-hint">松手传送,上滑取消</div>
|
<div class="vo-hint" id="voice-hint">松手传送,上滑取消</div>
|
||||||
<div class="vo-wave" id="voice-wave"></div>
|
<div class="vo-wave" id="voice-wave"></div>
|
||||||
|
<!-- 桌面点击模式的操作行:手机端按住说话用不到,CSS 里默认隐藏 -->
|
||||||
|
<div class="vo-actions" id="voice-actions">
|
||||||
|
<button type="button" class="vo-btn ghost" id="voice-cancel">取消</button>
|
||||||
|
<button type="button" class="vo-btn primary" id="voice-send">发送</button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<!-- 回到底部浮动按钮(搬自 index;上翻历史时出现、AI 输出中常驻转圈)。
|
<!-- 回到底部浮动按钮(搬自 index;上翻历史时出现、AI 输出中常驻转圈)。
|
||||||
放在 footer 内、相对 footer 顶边停靠:输入框长高/编辑条出现时不会被盖住 -->
|
放在 footer 内、相对 footer 顶边停靠:输入框长高/编辑条出现时不会被盖住 -->
|
||||||
<button class="scroll-bottom-btn hidden" id="scroll-bottom-btn" onclick="clickScrollBottom()" title="回到底部" aria-label="回到底部">
|
<button class="scroll-bottom-btn hidden" id="scroll-bottom-btn" onclick="clickScrollBottom()" title="回到底部" aria-label="回到底部">
|
||||||
<svg class="sb-arrow" viewBox="0 0 24 24"><polyline points="6 9 12 15 18 9"></polyline></svg>
|
<svg class="sb-arrow" viewBox="0 0 24 24"><use href="#i-chevron-down"/></svg>
|
||||||
<svg class="sb-spinner hidden" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"></circle><path d="M22 12a10 10 0 0 1-10 10"></path></svg>
|
<svg class="sb-spinner hidden" viewBox="0 0 24 24"><use href="#i-spinner"/></svg>
|
||||||
</button>
|
</button>
|
||||||
</footer>
|
</footer>
|
||||||
|
|
||||||
@@ -227,7 +325,7 @@
|
|||||||
<aside id="drawer" aria-label="对话历史">
|
<aside id="drawer" aria-label="对话历史">
|
||||||
<div class="drawer-search">
|
<div class="drawer-search">
|
||||||
<div class="search-box">
|
<div class="search-box">
|
||||||
<svg class="ic sm" viewBox="0 0 24 24"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>
|
<svg class="ic sm" viewBox="0 0 24 24"><use href="#i-search"/></svg>
|
||||||
<input type="search" id="search-input" placeholder="搜寻对话内容..." enterkeyhint="search">
|
<input type="search" id="search-input" placeholder="搜寻对话内容..." enterkeyhint="search">
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -238,10 +336,10 @@
|
|||||||
窄屏两个都隐藏:文件只保留输入行右侧的旧面板(不做两套)。选中项高亮。 -->
|
窄屏两个都隐藏:文件只保留输入行右侧的旧面板(不做两套)。选中项高亮。 -->
|
||||||
<div class="drawer-actions" id="drawer-actions">
|
<div class="drawer-actions" id="drawer-actions">
|
||||||
<button class="drawer-act" id="da-files" type="button" title="文件树" aria-label="文件树">
|
<button class="drawer-act" id="da-files" type="button" title="文件树" aria-label="文件树">
|
||||||
<svg viewBox="0 0 24 24"><path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path></svg>
|
<svg viewBox="0 0 24 24"><use href="#i-folder"/></svg>
|
||||||
</button>
|
</button>
|
||||||
<button class="drawer-act" id="da-settings" type="button" title="设置" aria-label="设置">
|
<button class="drawer-act" id="da-settings" type="button" title="设置" aria-label="设置">
|
||||||
<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="3"></circle><path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"></path></svg>
|
<svg viewBox="0 0 24 24"><use href="#i-gear"/></svg>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</aside>
|
</aside>
|
||||||
@@ -254,7 +352,7 @@
|
|||||||
<span class="files-panel-title">任务文件<span class="files-panel-size" id="files-panel-size" title="当前目录下全部文件总大小"></span></span>
|
<span class="files-panel-title">任务文件<span class="files-panel-size" id="files-panel-size" title="当前目录下全部文件总大小"></span></span>
|
||||||
<label class="file-upload" title="上传文件" aria-label="上传文件">
|
<label class="file-upload" title="上传文件" aria-label="上传文件">
|
||||||
<input type="file" id="file-input" multiple hidden>
|
<input type="file" id="file-input" multiple hidden>
|
||||||
<svg viewBox="0 0 24 24"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="17 8 12 3 7 8"></polyline><line x1="12" y1="3" x2="12" y2="15"></line></svg>
|
<svg viewBox="0 0 24 24"><use href="#i-upload-cloud"/></svg>
|
||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
<div class="files-crumbs hidden" id="files-crumbs" aria-label="目录路径"></div>
|
<div class="files-crumbs hidden" id="files-crumbs" aria-label="目录路径"></div>
|
||||||
@@ -270,10 +368,10 @@
|
|||||||
</div>
|
</div>
|
||||||
<div class="files-panel-actions">
|
<div class="files-panel-actions">
|
||||||
<button class="files-fab" id="files-bulk-download" title="批量下载" aria-label="批量下载" disabled>
|
<button class="files-fab" id="files-bulk-download" title="批量下载" aria-label="批量下载" disabled>
|
||||||
<svg viewBox="0 0 24 24"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="7 10 12 15 17 10"></polyline><line x1="12" y1="15" x2="12" y2="3"></line></svg>
|
<svg viewBox="0 0 24 24"><use href="#i-download"/></svg>
|
||||||
</button>
|
</button>
|
||||||
<button class="files-fab del" id="files-bulk-delete" title="批量删除" aria-label="批量删除" disabled>
|
<button class="files-fab del" id="files-bulk-delete" title="批量删除" aria-label="批量删除" disabled>
|
||||||
<svg viewBox="0 0 24 24"><path d="M3 6h18"/><path d="M8 6V4a1 1 0 0 1 1-1h6a1 1 0 0 1 1 1v2"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M10 11v6"/><path d="M14 11v6"/></svg>
|
<svg viewBox="0 0 24 24"><use href="#i-trash"/></svg>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -288,7 +386,7 @@
|
|||||||
<!-- 顶栏:左侧返回 + 中间标题 + 右侧操作按钮,风格与对话页 header 一致 -->
|
<!-- 顶栏:左侧返回 + 中间标题 + 右侧操作按钮,风格与对话页 header 一致 -->
|
||||||
<header class="header">
|
<header class="header">
|
||||||
<button class="icon-btn" id="set-back-btn" title="返回" aria-label="返回">
|
<button class="icon-btn" id="set-back-btn" title="返回" aria-label="返回">
|
||||||
<svg class="ic" viewBox="0 0 24 24"><polyline points="15 18 9 12 15 6"></polyline></svg>
|
<svg class="ic" viewBox="0 0 24 24"><use href="#i-chevron-left"/></svg>
|
||||||
</button>
|
</button>
|
||||||
<div class="header-center"><div class="header-title" id="set-title">设置</div></div>
|
<div class="header-center"><div class="header-title" id="set-title">设置</div></div>
|
||||||
<div class="header-right" id="set-actions"><!-- JS 按页注入操作按钮 --></div>
|
<div class="header-right" id="set-actions"><!-- JS 按页注入操作按钮 --></div>
|
||||||
@@ -301,7 +399,7 @@
|
|||||||
<div id="skill-create-modal" class="modal-overlay hidden" onclick="if(event.target===this)sUI.closeCreate()">
|
<div id="skill-create-modal" class="modal-overlay hidden" onclick="if(event.target===this)sUI.closeCreate()">
|
||||||
<div class="modal">
|
<div class="modal">
|
||||||
<button class="modal-close-btn" onclick="sUI.closeCreate()">
|
<button class="modal-close-btn" onclick="sUI.closeCreate()">
|
||||||
<svg viewBox="0 0 24 24"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
|
<svg viewBox="0 0 24 24"><use href="#i-x-line-b"/></svg>
|
||||||
</button>
|
</button>
|
||||||
<h3>新建技能</h3>
|
<h3>新建技能</h3>
|
||||||
<input type="text" id="skill-new-name" placeholder="技能名(字母/数字/-/_)">
|
<input type="text" id="skill-new-name" placeholder="技能名(字母/数字/-/_)">
|
||||||
@@ -314,7 +412,7 @@
|
|||||||
<div id="model-edit-modal" class="modal-overlay hidden" onclick="if(event.target===this)sUI.mClose()">
|
<div id="model-edit-modal" class="modal-overlay hidden" onclick="if(event.target===this)sUI.mClose()">
|
||||||
<div class="modal modal-wide">
|
<div class="modal modal-wide">
|
||||||
<button class="modal-close-btn" onclick="sUI.mClose()">
|
<button class="modal-close-btn" onclick="sUI.mClose()">
|
||||||
<svg viewBox="0 0 24 24"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
|
<svg viewBox="0 0 24 24"><use href="#i-x-line-b"/></svg>
|
||||||
</button>
|
</button>
|
||||||
<h3 id="mpe-title">编辑平台</h3>
|
<h3 id="mpe-title">编辑平台</h3>
|
||||||
<!-- 平台预设:仅新增平台时展示,点选即填好 url/类型并给模型卡带上该平台的参数缺省 -->
|
<!-- 平台预设:仅新增平台时展示,点选即填好 url/类型并给模型卡带上该平台的参数缺省 -->
|
||||||
@@ -340,7 +438,7 @@
|
|||||||
<div id="user-edit-modal" class="modal-overlay hidden" onclick="if(event.target===this)sUI.closeUserModal()">
|
<div id="user-edit-modal" class="modal-overlay hidden" onclick="if(event.target===this)sUI.closeUserModal()">
|
||||||
<div class="modal">
|
<div class="modal">
|
||||||
<button class="modal-close-btn" onclick="sUI.closeUserModal()">
|
<button class="modal-close-btn" onclick="sUI.closeUserModal()">
|
||||||
<svg viewBox="0 0 24 24"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
|
<svg viewBox="0 0 24 24"><use href="#i-x-line-b"/></svg>
|
||||||
</button>
|
</button>
|
||||||
<h3 id="ue-title">添加用户</h3>
|
<h3 id="ue-title">添加用户</h3>
|
||||||
<input type="text" id="ue-user" placeholder="用户名(字母/数字/下划线)" autocomplete="off">
|
<input type="text" id="ue-user" placeholder="用户名(字母/数字/下划线)" autocomplete="off">
|
||||||
@@ -362,7 +460,7 @@
|
|||||||
<div id="mcp-edit-modal" class="modal-overlay hidden" onclick="if(event.target===this)mcpUI.close()">
|
<div id="mcp-edit-modal" class="modal-overlay hidden" onclick="if(event.target===this)mcpUI.close()">
|
||||||
<div class="modal modal-wide">
|
<div class="modal modal-wide">
|
||||||
<button class="modal-close-btn" onclick="mcpUI.close()">
|
<button class="modal-close-btn" onclick="mcpUI.close()">
|
||||||
<svg viewBox="0 0 24 24"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
|
<svg viewBox="0 0 24 24"><use href="#i-x-line-b"/></svg>
|
||||||
</button>
|
</button>
|
||||||
<h3 id="mce-title">编辑 MCP 服务</h3>
|
<h3 id="mce-title">编辑 MCP 服务</h3>
|
||||||
<input type="text" id="mce-name" placeholder="服务名">
|
<input type="text" id="mce-name" placeholder="服务名">
|
||||||
@@ -400,7 +498,7 @@
|
|||||||
<div id="schedule-modal" class="modal-overlay hidden" onclick="if(event.target===this)closeScheduleModal()">
|
<div id="schedule-modal" class="modal-overlay hidden" onclick="if(event.target===this)closeScheduleModal()">
|
||||||
<div class="modal">
|
<div class="modal">
|
||||||
<button class="modal-close-btn" onclick="closeScheduleModal()">
|
<button class="modal-close-btn" onclick="closeScheduleModal()">
|
||||||
<svg viewBox="0 0 24 24"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
|
<svg viewBox="0 0 24 24"><use href="#i-x-line-b"/></svg>
|
||||||
</button>
|
</button>
|
||||||
<h3 id="schedule-modal-title">定时任务</h3>
|
<h3 id="schedule-modal-title">定时任务</h3>
|
||||||
<div class="sched-row">
|
<div class="sched-row">
|
||||||
@@ -433,7 +531,7 @@
|
|||||||
<div id="confirm-modal" class="modal-overlay hidden" onclick="if(event.target===this)confirmClose(null)">
|
<div id="confirm-modal" class="modal-overlay hidden" onclick="if(event.target===this)confirmClose(null)">
|
||||||
<div class="modal">
|
<div class="modal">
|
||||||
<button class="modal-close-btn" onclick="confirmClose(null)" aria-label="关闭">
|
<button class="modal-close-btn" onclick="confirmClose(null)" aria-label="关闭">
|
||||||
<svg viewBox="0 0 24 24"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
|
<svg viewBox="0 0 24 24"><use href="#i-x-line-b"/></svg>
|
||||||
</button>
|
</button>
|
||||||
<h3 id="confirm-title">请确认</h3>
|
<h3 id="confirm-title">请确认</h3>
|
||||||
<div class="modal-text" id="confirm-text"></div>
|
<div class="modal-text" id="confirm-text"></div>
|
||||||
@@ -449,7 +547,7 @@
|
|||||||
<div id="prompt-modal" class="modal-overlay hidden" onclick="if(event.target===this)promptCancel()">
|
<div id="prompt-modal" class="modal-overlay hidden" onclick="if(event.target===this)promptCancel()">
|
||||||
<div class="modal">
|
<div class="modal">
|
||||||
<button class="modal-close-btn" onclick="promptCancel()">
|
<button class="modal-close-btn" onclick="promptCancel()">
|
||||||
<svg viewBox="0 0 24 24"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
|
<svg viewBox="0 0 24 24"><use href="#i-x-line-b"/></svg>
|
||||||
</button>
|
</button>
|
||||||
<h3 id="prompt-title">请输入</h3>
|
<h3 id="prompt-title">请输入</h3>
|
||||||
<input type="text" id="prompt-input">
|
<input type="text" id="prompt-input">
|
||||||
@@ -469,7 +567,7 @@
|
|||||||
<p class="msw-sub" id="bind-model-sub">选择一个模型继续当前会话</p>
|
<p class="msw-sub" id="bind-model-sub">选择一个模型继续当前会话</p>
|
||||||
</div>
|
</div>
|
||||||
<button class="modal-close-btn" onclick="closeModelSwitch()">
|
<button class="modal-close-btn" onclick="closeModelSwitch()">
|
||||||
<svg viewBox="0 0 24 24"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
|
<svg viewBox="0 0 24 24"><use href="#i-x-line-b"/></svg>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<div class="msw-list" id="bind-model-list"></div>
|
<div class="msw-list" id="bind-model-list"></div>
|
||||||
@@ -494,23 +592,23 @@
|
|||||||
<span class="pv-addr">
|
<span class="pv-addr">
|
||||||
<input class="pv-title" id="pv-title" aria-label="文件路径或网址">
|
<input class="pv-title" id="pv-title" aria-label="文件路径或网址">
|
||||||
<button class="icon-btn hidden" id="pv-refresh" title="重新载入" aria-label="重新载入">
|
<button class="icon-btn hidden" id="pv-refresh" title="重新载入" aria-label="重新载入">
|
||||||
<svg class="ic sm" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="23 4 23 10 17 10"></polyline><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"></path></svg>
|
<svg class="ic sm" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><use href="#i-refresh"/></svg>
|
||||||
</button>
|
</button>
|
||||||
<button class="icon-btn hidden" id="pv-popup" title="新窗口打开" aria-label="新窗口打开">
|
<button class="icon-btn hidden" id="pv-popup" title="新窗口打开" aria-label="新窗口打开">
|
||||||
<svg class="ic sm" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"></path><polyline points="15 3 21 3 21 9"></polyline><line x1="10" y1="14" x2="21" y2="3"></line></svg>
|
<svg class="ic sm" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><use href="#i-external"/></svg>
|
||||||
</button>
|
</button>
|
||||||
</span>
|
</span>
|
||||||
<span class="pv-actions">
|
<span class="pv-actions">
|
||||||
<!-- 源码钮:只在当前内容有源文本时出现(md/文本/代码/html/svg),点了在预览与原文间切换 -->
|
<!-- 源码钮:只在当前内容有源文本时出现(md/文本/代码/html/svg),点了在预览与原文间切换 -->
|
||||||
<button class="icon-btn hidden" id="pv-src" title="查看源码" aria-label="查看源码">
|
<button class="icon-btn hidden" id="pv-src" title="查看源码" aria-label="查看源码">
|
||||||
<svg class="ic sm" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path><circle cx="12" cy="12" r="3"></circle></svg>
|
<svg class="ic sm" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><use href="#i-eye"/></svg>
|
||||||
</button>
|
</button>
|
||||||
<button class="icon-btn hidden" id="pv-download" title="下载文件" aria-label="下载文件">
|
<button class="icon-btn hidden" id="pv-download" title="下载文件" aria-label="下载文件">
|
||||||
<svg class="ic sm" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="7 10 12 15 17 10"></polyline><line x1="12" y1="15" x2="12" y2="3"></line></svg>
|
<svg class="ic sm" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><use href="#i-download"/></svg>
|
||||||
</button>
|
</button>
|
||||||
<button class="icon-btn" id="pv-max" title="放大" aria-label="放大">
|
<button class="icon-btn" id="pv-max" title="放大" aria-label="放大">
|
||||||
<svg class="ic sm" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M8 3H5a2 2 0 0 0-2 2v3"></path><path d="M21 8V5a2 2 0 0 0-2-2h-3"></path><path d="M16 21h3a2 2 0 0 0 2-2v-3"></path><path d="M3 16v3a2 2 0 0 0 2 2h3"></path></svg>
|
<svg class="ic sm" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><use href="#i-maximize"/></svg>
|
||||||
<svg class="ic sm hidden" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M8 3v3a2 2 0 0 1-2 2H3"></path><path d="M21 8h-3a2 2 0 0 1-2-2V3"></path><path d="M3 16h3a2 2 0 0 1 2 2v3"></path><path d="M16 21v-3a2 2 0 0 1 2-2h3"></path></svg>
|
<svg class="ic sm hidden" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><use href="#i-minimize"/></svg>
|
||||||
</button>
|
</button>
|
||||||
<button class="icon-btn" id="pv-close" title="关闭预览" aria-label="关闭预览">✕</button>
|
<button class="icon-btn" id="pv-close" title="关闭预览" aria-label="关闭预览">✕</button>
|
||||||
</span>
|
</span>
|
||||||
@@ -527,11 +625,11 @@
|
|||||||
<span class="fs-name" id="fs-file-name"></span>
|
<span class="fs-name" id="fs-file-name"></span>
|
||||||
<!-- 源码切换钮:仅当当前内容有源文本时显隐(toggleFsSrc 在渲染视图/源码面板间互切) -->
|
<!-- 源码切换钮:仅当当前内容有源文本时显隐(toggleFsSrc 在渲染视图/源码面板间互切) -->
|
||||||
<button class="fs-btn hidden" id="fs-src-btn" title="显示源码" aria-label="显示源码">
|
<button class="fs-btn hidden" id="fs-src-btn" title="显示源码" aria-label="显示源码">
|
||||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path><circle cx="12" cy="12" r="3"></circle></svg>
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><use href="#i-eye"/></svg>
|
||||||
</button>
|
</button>
|
||||||
<!-- 复制源码:显隐与 eye 一致(有源文本才出现);HTML/SVG/MD/代码通用 -->
|
<!-- 复制源码:显隐与 eye 一致(有源文本才出现);HTML/SVG/MD/代码通用 -->
|
||||||
<button class="fs-btn hidden" id="fs-copy-btn" title="复制源码" aria-label="复制源码">
|
<button class="fs-btn hidden" id="fs-copy-btn" title="复制源码" aria-label="复制源码">
|
||||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2"></rect><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path></svg>
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><use href="#i-copy"/></svg>
|
||||||
</button>
|
</button>
|
||||||
<button class="fs-btn" onclick="closeFullscreen()" title="关闭" aria-label="关闭">✕</button>
|
<button class="fs-btn" onclick="closeFullscreen()" title="关闭" aria-label="关闭">✕</button>
|
||||||
</div>
|
</div>
|
||||||
@@ -542,7 +640,7 @@
|
|||||||
<!-- 拖拽上传提示层:window 级 dragenter 时显示;pointer-events:none,不参与命中测试(逻辑见 js/files.js) -->
|
<!-- 拖拽上传提示层:window 级 dragenter 时显示;pointer-events:none,不参与命中测试(逻辑见 js/files.js) -->
|
||||||
<div id="drop-overlay" class="hidden" aria-hidden="true">
|
<div id="drop-overlay" class="hidden" aria-hidden="true">
|
||||||
<div class="drop-hint">
|
<div class="drop-hint">
|
||||||
<svg viewBox="0 0 24 24" class="ic"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="17 8 12 3 7 8"></polyline><line x1="12" y1="3" x2="12" y2="15"></line></svg>
|
<svg viewBox="0 0 24 24" class="ic"><use href="#i-upload-cloud"/></svg>
|
||||||
<span>松开即可上传</span>
|
<span>松开即可上传</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -32,13 +32,13 @@
|
|||||||
// 删除本条:仅已落库消息可删(传 m.id);流式未落库时无 id,不渲染
|
// 删除本条:仅已落库消息可删(传 m.id);流式未落库时无 id,不渲染
|
||||||
const del = msgId
|
const del = msgId
|
||||||
? '<button class="act act-del" title="删除本条" data-msg-id="' + msgId + '">' +
|
? '<button class="act act-del" title="删除本条" data-msg-id="' + msgId + '">' +
|
||||||
'<svg class="ic sm" viewBox="0 0 24 24"><path d="M18 6 6 18"></path><path d="m6 6 12 12"></path></svg>' +
|
'<svg class="ic sm" viewBox="0 0 24 24"><use href="#i-x-path"/></svg>' +
|
||||||
'</button>'
|
'</button>'
|
||||||
: '';
|
: '';
|
||||||
// 编辑并重发:只给未压缩的用户消息(调用方传 canEdit);带 b64 回填输入框,避免从 DOM 反推
|
// 编辑并重发:只给未压缩的用户消息(调用方传 canEdit);带 b64 回填输入框,避免从 DOM 反推
|
||||||
const edit = canEdit && msgId
|
const edit = canEdit && msgId
|
||||||
? '<button class="act act-edit" title="编辑并重发" data-msg-id="' + msgId + '" data-b64="' + b64 + '">' +
|
? '<button class="act act-edit" title="编辑并重发" data-msg-id="' + msgId + '" data-b64="' + b64 + '">' +
|
||||||
'<svg class="ic sm" viewBox="0 0 24 24"><path d="M12 20h9"></path><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4z"></path></svg>' +
|
'<svg class="ic sm" viewBox="0 0 24 24"><use href="#i-pencil"/></svg>' +
|
||||||
'</button>'
|
'</button>'
|
||||||
: '';
|
: '';
|
||||||
const u = normUsage(usage);
|
const u = normUsage(usage);
|
||||||
@@ -49,7 +49,7 @@
|
|||||||
'<span>' + fmtTime(ts) + '</span>' +
|
'<span>' + fmtTime(ts) + '</span>' +
|
||||||
usageHtml +
|
usageHtml +
|
||||||
'<button class="act act-copy" title="复制" data-b64="' + b64 + '">' +
|
'<button class="act act-copy" title="复制" data-b64="' + b64 + '">' +
|
||||||
'<svg class="ic sm" viewBox="0 0 24 24"><rect x="9" y="9" width="13" height="13" rx="2"></rect><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path></svg>' +
|
'<svg class="ic sm" viewBox="0 0 24 24"><use href="#i-copy"/></svg>' +
|
||||||
'</button>' +
|
'</button>' +
|
||||||
edit +
|
edit +
|
||||||
del +
|
del +
|
||||||
@@ -100,7 +100,7 @@
|
|||||||
// 历史重渲染默认收起(与原设计一致),流式阶段的展开行为由 ensureStreamThinkPanel 显式控制。
|
// 历史重渲染默认收起(与原设计一致),流式阶段的展开行为由 ensureStreamThinkPanel 显式控制。
|
||||||
// 复制按钮走 onCopyClick 统一代理:点击时从 DOM 取思考全文(不依赖 b64,流式增量也能复制)
|
// 复制按钮走 onCopyClick 统一代理:点击时从 DOM 取思考全文(不依赖 b64,流式增量也能复制)
|
||||||
const THINK_COPY_BTN = '<button class="act act-copy" title="复制思考内容">' +
|
const THINK_COPY_BTN = '<button class="act act-copy" title="复制思考内容">' +
|
||||||
'<svg class="ic sm" viewBox="0 0 24 24"><rect x="9" y="9" width="13" height="13" rx="2"></rect><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path></svg>' +
|
'<svg class="ic sm" viewBox="0 0 24 24"><use href="#i-copy"/></svg>' +
|
||||||
'</button>';
|
'</button>';
|
||||||
function thinkPanelHtml(text) {
|
function thinkPanelHtml(text) {
|
||||||
return '<details class="msg-think"><summary>思考过程' + THINK_COPY_BTN + '</summary><div class="msg-think-body">' + esc(text) + '</div></details>';
|
return '<details class="msg-think"><summary>思考过程' + THINK_COPY_BTN + '</summary><div class="msg-think-body">' + esc(text) + '</div></details>';
|
||||||
@@ -112,7 +112,7 @@
|
|||||||
// 复制文本在点击时从 pre.textContent 现取(onCopyClick 的 .code-wrap 分支),不嵌 b64、不怕内容后续变化。
|
// 复制文本在点击时从 pre.textContent 现取(onCopyClick 的 .code-wrap 分支),不嵌 b64、不怕内容后续变化。
|
||||||
// 只碰 .md 里的 pre:工具卡 / 思考区已有自己的复制按钮,行内 code 不加。
|
// 只碰 .md 里的 pre:工具卡 / 思考区已有自己的复制按钮,行内 code 不加。
|
||||||
const CODE_COPY_BTN = '<button class="act act-copy" type="button" title="复制代码">' +
|
const CODE_COPY_BTN = '<button class="act act-copy" type="button" title="复制代码">' +
|
||||||
'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2"></rect><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path></svg>' +
|
'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><use href="#i-copy"/></svg>' +
|
||||||
'</button>';
|
'</button>';
|
||||||
function decorateCodePre(root) {
|
function decorateCodePre(root) {
|
||||||
if (!root || !root.querySelectorAll) return;
|
if (!root || !root.querySelectorAll) return;
|
||||||
@@ -172,14 +172,14 @@
|
|||||||
if (!text) return '';
|
if (!text) return '';
|
||||||
const b64 = btoa(unescape(encodeURIComponent(text)));
|
const b64 = btoa(unescape(encodeURIComponent(text)));
|
||||||
return '<button class="act act-copy" title="复制参数与结果" data-b64="' + b64 + '">' +
|
return '<button class="act act-copy" title="复制参数与结果" data-b64="' + b64 + '">' +
|
||||||
'<svg class="ic sm" viewBox="0 0 24 24"><rect x="9" y="9" width="13" height="13" rx="2"></rect><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path></svg></button>';
|
'<svg class="ic sm" viewBox="0 0 24 24"><use href="#i-copy"/></svg></button>';
|
||||||
}
|
}
|
||||||
// 工具卡「删除本条」:删的是 tool 消息行;后端会把它在父 assistant 里的调用同步摘除。
|
// 工具卡「删除本条」:删的是 tool 消息行;后端会把它在父 assistant 里的调用同步摘除。
|
||||||
// msgId = tool 消息的库行 id(历史渲染传 m.id;实时由 tool_result 事件的 msg_id 携带)
|
// msgId = tool 消息的库行 id(历史渲染传 m.id;实时由 tool_result 事件的 msg_id 携带)
|
||||||
function toolDelBtnHtml(msgId) {
|
function toolDelBtnHtml(msgId) {
|
||||||
if (!msgId) return '';
|
if (!msgId) return '';
|
||||||
return '<button class="act act-del" title="删除本条" data-msg-id="' + msgId + '">' +
|
return '<button class="act act-del" title="删除本条" data-msg-id="' + msgId + '">' +
|
||||||
'<svg class="ic sm" viewBox="0 0 24 24"><path d="M18 6 6 18"></path><path d="m6 6 12 12"></path></svg></button>';
|
'<svg class="ic sm" viewBox="0 0 24 24"><use href="#i-x-path"/></svg></button>';
|
||||||
}
|
}
|
||||||
function renderToolCard(id, name, argsStr, createdAt, opts) {
|
function renderToolCard(id, name, argsStr, createdAt, opts) {
|
||||||
const div = document.createElement('div');
|
const div = document.createElement('div');
|
||||||
@@ -380,6 +380,7 @@
|
|||||||
}
|
}
|
||||||
// 历史渲染收口:给本轮新渲染出的代码块补复制按钮(目标可能是分页离屏容器,装饰后再随节点搬迁)
|
// 历史渲染收口:给本轮新渲染出的代码块补复制按钮(目标可能是分页离屏容器,装饰后再随节点搬迁)
|
||||||
decorateCodePre(target);
|
decorateCodePre(target);
|
||||||
|
pvHighlightMdCode(target); // 对话正文里的围栏代码块也上色(与预览同一套)
|
||||||
return { closeArc };
|
return { closeArc };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -48,7 +48,13 @@
|
|||||||
if (typeof marked !== 'undefined') marked.setOptions({ breaks: true, gfm: true });
|
if (typeof marked !== 'undefined') marked.setOptions({ breaks: true, gfm: true });
|
||||||
function mdHtml(text) {
|
function mdHtml(text) {
|
||||||
if (typeof marked === 'undefined') return { html: esc(text), fmt: false };
|
if (typeof marked === 'undefined') return { html: esc(text), fmt: false };
|
||||||
try { return { html: marked.parse(text || ''), fmt: true }; }
|
try {
|
||||||
|
// 公式先抠成占位、marked 解析完再填回 KaTeX 输出(见 math.js)
|
||||||
|
const html = typeof mdParseWithMath === 'function'
|
||||||
|
? mdParseWithMath(text || '', marked)
|
||||||
|
: marked.parse(text || '');
|
||||||
|
return { html: html, fmt: true };
|
||||||
|
}
|
||||||
catch (_) { return { html: esc(text), fmt: false }; }
|
catch (_) { return { html: esc(text), fmt: false }; }
|
||||||
}
|
}
|
||||||
function fmtTime(ts) {
|
function fmtTime(ts) {
|
||||||
@@ -148,11 +154,11 @@
|
|||||||
const MODES = {
|
const MODES = {
|
||||||
secretary: {
|
secretary: {
|
||||||
label: '文秘助理', hint: '支持文字输入,可起草、润色、整理文书',
|
label: '文秘助理', hint: '支持文字输入,可起草、润色、整理文书',
|
||||||
icon: '<svg class="header-mode-icon" viewBox="0 0 24 24"><path d="M6 3h12l4 6-10 13L2 9z"></path><polyline points="2 9 22 9"></polyline><polyline points="10 3 8 9 12 22"></polyline><polyline points="14 3 16 9 12 22"></polyline></svg>',
|
icon: '<svg class="header-mode-icon" viewBox="0 0 24 24"><use href="#i-gem"/></svg>',
|
||||||
},
|
},
|
||||||
vision: {
|
vision: {
|
||||||
label: '识图专家', hint: '支持图片识别输入',
|
label: '识图专家', hint: '支持图片识别输入',
|
||||||
icon: '<svg class="header-mode-icon" viewBox="0 0 24 24"><rect x="3" y="3" width="18" height="18" rx="2"></rect><circle cx="8.5" cy="8.5" r="1.5"></circle><polyline points="21 15 16 10 5 21"></polyline></svg>',
|
icon: '<svg class="header-mode-icon" viewBox="0 0 24 24"><use href="#i-image"/></svg>',
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -8,23 +8,25 @@
|
|||||||
// 依赖(全局):state $ req toast downloadFile confirmModal openFilePreview
|
// 依赖(全局):state $ req toast downloadFile confirmModal openFilePreview
|
||||||
'use strict';
|
'use strict';
|
||||||
(function () {
|
(function () {
|
||||||
const SVG_FOLDER = '<svg class="ic sm" viewBox="0 0 24 24"><path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/></svg>';
|
const SVG_FOLDER = '<svg class="ic sm" viewBox="0 0 24 24"><use href="#i-folder"/></svg>';
|
||||||
const SVG_FILE = '<svg class="ic sm" viewBox="0 0 24 24"><path d="M6 3h8l4 4v14H6z"/><path d="M14 3v4h4"/></svg>';
|
const SVG_FILE = '<svg class="ic sm" viewBox="0 0 24 24"><use href="#i-file"/></svg>';
|
||||||
const SVG_LINK = '<svg class="ic sm" viewBox="0 0 24 24"><path d="M10 13a5 5 0 0 0 7 0l2-2a5 5 0 0 0-7-7l-1 1"/><path d="M14 11a5 5 0 0 0-7 0l-2 2a5 5 0 0 0 7 7l1-1"/></svg>';
|
const SVG_LINK = '<svg class="ic sm" viewBox="0 0 24 24"><use href="#i-link"/></svg>';
|
||||||
const SVG_REVEAL = '<svg class="ic sm" viewBox="0 0 24 24"><path d="M14 4h6v6"/><path d="M20 4l-9 9"/><path d="M19 14v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1h5"/></svg>';
|
const SVG_REVEAL = '<svg class="ic sm" viewBox="0 0 24 24"><use href="#i-external-b"/></svg>';
|
||||||
const SVG_REFRESH = '<svg class="ic sm" viewBox="0 0 24 24"><path d="M20 12a8 8 0 1 1-2.3-5.7"/><path d="M20 4v5h-5"/></svg>';
|
const SVG_REFRESH = '<svg class="ic sm" viewBox="0 0 24 24"><use href="#i-reload"/></svg>';
|
||||||
const SVG_TERM = '<svg class="ic sm" viewBox="0 0 24 24"><rect x="3" y="4" width="18" height="16" rx="2"/><path d="M7 9l3 3-3 3"/><path d="M13 15h4"/></svg>';
|
const SVG_TERM = '<svg class="ic sm" viewBox="0 0 24 24"><use href="#i-terminal"/></svg>';
|
||||||
const SVG_VCS = '<svg class="ic sm" viewBox="0 0 24 24"><circle cx="6" cy="5" r="2"/><circle cx="6" cy="19" r="2"/><circle cx="18" cy="7" r="2"/><path d="M6 7v10"/><path d="M18 9v1a4 4 0 0 1-4 4H9"/></svg>';
|
const SVG_VCS = '<svg class="ic sm" viewBox="0 0 24 24"><use href="#i-git"/></svg>';
|
||||||
const SVG_EYE = '<svg class="ic sm" viewBox="0 0 24 24"><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12z"/><circle cx="12" cy="12" r="2.6"/></svg>';
|
const SVG_EYE = '<svg class="ic sm" viewBox="0 0 24 24"><use href="#i-eye-sm"/></svg>';
|
||||||
const SVG_DL = '<svg viewBox="0 0 24 24"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>';
|
const SVG_DL = '<svg viewBox="0 0 24 24"><use href="#i-download"/></svg>';
|
||||||
const SVG_DEL = '<svg viewBox="0 0 24 24"><path d="M3 6h18"/><path d="M8 6V4a1 1 0 0 1 1-1h6a1 1 0 0 1 1 1v2"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M10 11v6"/><path d="M14 11v6"/></svg>';
|
const SVG_DEL = '<svg viewBox="0 0 24 24"><use href="#i-trash"/></svg>';
|
||||||
const SVG_REVEAL_SM = '<svg viewBox="0 0 24 24"><path d="M14 4h6v6"/><path d="M20 4l-9 9"/><path d="M19 14v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1h5"/></svg>';
|
const SVG_REVEAL_SM = '<svg viewBox="0 0 24 24"><use href="#i-external-b"/></svg>';
|
||||||
|
const SVG_AT = '<span class="at-glyph">@</span>';
|
||||||
|
|
||||||
let localCapable = false; // local 启动器:才显示「在 Finder/终端中打开」
|
let localCapable = false; // local 启动器:才显示「在 Finder/终端中打开」
|
||||||
let showHidden = false;
|
let showHidden = false;
|
||||||
let expanded = new Set(['']); // 已展开的相对目录('' = 根)
|
let expanded = new Set(['']); // 已展开的相对目录('' = 根)
|
||||||
let cache = new Map(); // rel -> /tree 响应
|
let cache = new Map(); // rel -> /tree 响应
|
||||||
let loading = new Map(); // rel -> Promise(并发去重)
|
let loading = new Map(); // rel -> Promise(并发去重)
|
||||||
|
let emptyDirs = new Map(); // rel -> 目录 mtimeMs:确认空着的目录,mtime 没变就不必再请求
|
||||||
let gen = 0; // 会话切换/刷新时自增,防止旧请求回填到新树的缓存
|
let gen = 0; // 会话切换/刷新时自增,防止旧请求回填到新树的缓存
|
||||||
// 多选:rel -> 'dir' | 'file'。勾目录表示整个目录(下载打成一个 zip、删除递归),
|
// 多选:rel -> 'dir' | 'file'。勾目录表示整个目录(下载打成一个 zip、删除递归),
|
||||||
// 所以勾目录会吃掉子项,勾子项会把祖先目录降级掉,见 toggleSel。
|
// 所以勾目录会吃掉子项,勾子项会把祖先目录降级掉,见 toggleSel。
|
||||||
@@ -35,7 +37,7 @@
|
|||||||
gen++;
|
gen++;
|
||||||
cache = new Map();
|
cache = new Map();
|
||||||
loading = new Map();
|
loading = new Map();
|
||||||
if (!keepExpanded) { expanded = new Set(['']); sel.clear(); }
|
if (!keepExpanded) { expanded = new Set(['']); sel.clear(); emptyDirs = new Map(); }
|
||||||
}
|
}
|
||||||
|
|
||||||
function sid() { return (state && state.sessionId) || ''; }
|
function sid() { return (state && state.sessionId) || ''; }
|
||||||
@@ -47,15 +49,24 @@
|
|||||||
parent.appendChild(el);
|
parent.appendChild(el);
|
||||||
}
|
}
|
||||||
|
|
||||||
function openDir(rel) {
|
function openDir(rel, dirMtime) {
|
||||||
if (cache.has(rel)) return Promise.resolve(cache.get(rel));
|
if (cache.has(rel)) return Promise.resolve(cache.get(rel));
|
||||||
if (loading.has(rel)) return loading.get(rel);
|
if (loading.has(rel)) return loading.get(rel);
|
||||||
if (!sid()) return Promise.resolve(null);
|
if (!sid()) return Promise.resolve(null);
|
||||||
|
// 已知空目录且目录自身 mtime 未变(增删子项才会变):跳过请求,直接给空结果
|
||||||
|
if (dirMtime != null && emptyDirs.get(rel) === dirMtime) {
|
||||||
|
return Promise.resolve({ dir: rel, total: 0, capped: false, entries: [] });
|
||||||
|
}
|
||||||
const url = '/api/sessions/' + encodeURIComponent(sid()) + '/tree?dir=' +
|
const url = '/api/sessions/' + encodeURIComponent(sid()) + '/tree?dir=' +
|
||||||
encodeURIComponent(rel) + (showHidden ? '&hidden=1' : '');
|
encodeURIComponent(rel) + (showHidden ? '&hidden=1' : '');
|
||||||
const myGen = gen;
|
const myGen = gen;
|
||||||
const p = req('GET', url).then(function (data) {
|
const p = req('GET', url).then(function (data) {
|
||||||
if (myGen === gen) { cache.set(rel, data); loading.delete(rel); }
|
if (myGen === gen) {
|
||||||
|
cache.set(rel, data); loading.delete(rel);
|
||||||
|
const n = (data && data.entries) ? data.entries.length : 0;
|
||||||
|
if (!n && dirMtime != null) emptyDirs.set(rel, dirMtime);
|
||||||
|
else if (n) emptyDirs.delete(rel);
|
||||||
|
}
|
||||||
return data;
|
return data;
|
||||||
}, function (e) {
|
}, function (e) {
|
||||||
if (myGen === gen) loading.delete(rel);
|
if (myGen === gen) loading.delete(rel);
|
||||||
@@ -87,13 +98,12 @@
|
|||||||
if (expanded.has(ent.rel)) row.classList.add('open');
|
if (expanded.has(ent.rel)) row.classList.add('open');
|
||||||
}
|
}
|
||||||
if (ent.type === 'link') row.classList.add('is-link');
|
if (ent.type === 'link') row.classList.add('is-link');
|
||||||
if (ent.ignored) row.classList.add('is-ignored');
|
|
||||||
|
|
||||||
// 不画展开箭头:文件夹图标已经说明可以点,点行任意位置都能展开/收起。
|
// 不画展开箭头:文件夹图标已经说明可以点,点行任意位置都能展开/收起。
|
||||||
|
|
||||||
// 勾选框:hover 或已选中时淡入,但占位始终在,避免 hover 时文件名左右跳。
|
// 勾选框:hover 或已选中时淡入,但占位始终在,避免 hover 时文件名左右跳。
|
||||||
// 忽略的大目录和软链不参与批量操作(后端也不让删),所以不给勾选框。
|
// 软链不参与批量操作(后端也不让删),所以不给勾选框。
|
||||||
if (!ent.ignored && ent.type !== 'link') {
|
if (ent.type !== 'link') {
|
||||||
const chk = document.createElement('span');
|
const chk = document.createElement('span');
|
||||||
chk.className = 'tree-check';
|
chk.className = 'tree-check';
|
||||||
chk.setAttribute('role', 'checkbox');
|
chk.setAttribute('role', 'checkbox');
|
||||||
@@ -114,32 +124,31 @@
|
|||||||
name.textContent = ent.name;
|
name.textContent = ent.name;
|
||||||
row.appendChild(name);
|
row.appendChild(name);
|
||||||
|
|
||||||
if (ent.ignored) {
|
|
||||||
row.title = ent.rel + '(已忽略的大目录/构建产物)';
|
|
||||||
return row;
|
|
||||||
}
|
|
||||||
// 行内动作:服务器形态给「下载 / 删除」;local 本就跑在同一台机器上,
|
// 行内动作:服务器形态给「下载 / 删除」;local 本就跑在同一台机器上,
|
||||||
// 「下载」到本地是多余的(用 Finder 直接看原文件更顺),所以换成「在 Finder 中显示」。
|
// 「下载」到本地是多余的(用 Finder 直接看原文件更顺),所以换成「在 Finder 中显示」。
|
||||||
|
// @ 引用排最前:它是「往输入框送东西」的动作,和后面的下载 / Finder / 删除(对文件本身动手)分开
|
||||||
|
row.appendChild(actBtn('at', ent.type === 'dir' ? '引用此目录' : '引用到输入框', SVG_AT, false));
|
||||||
if (ent.type === 'file' && !localCapable) row.appendChild(actBtn('download', '下载', SVG_DL, false));
|
if (ent.type === 'file' && !localCapable) row.appendChild(actBtn('download', '下载', SVG_DL, false));
|
||||||
if (localCapable) row.appendChild(actBtn('reveal', '在 Finder 中显示', SVG_REVEAL_SM, false));
|
if (localCapable) row.appendChild(actBtn('reveal', '在 Finder 中显示', SVG_REVEAL_SM, false));
|
||||||
row.appendChild(actBtn('delete', '删除', SVG_DEL, true));
|
row.appendChild(actBtn('delete', '删除', SVG_DEL, true));
|
||||||
return row;
|
return row;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function renderDirInto(container, rel, depth) {
|
async function renderDirInto(container, rel, depth, dirMtime) {
|
||||||
container.innerHTML = '';
|
container.innerHTML = '';
|
||||||
const data = await openDir(rel);
|
const data = await openDir(rel, dirMtime);
|
||||||
if (!data) return;
|
if (!data) return;
|
||||||
const frag = document.createDocumentFragment();
|
const frag = document.createDocumentFragment();
|
||||||
const list = data.entries || [];
|
const list = data.entries || [];
|
||||||
if (!list.length) tip(frag, '(空目录)');
|
// 只在根目录给空提示:子目录展开后本来就该「看不出变化」,根节点全空白则分不清是空还是没加载
|
||||||
|
if (!list.length && !rel) tip(frag, '(空目录)');
|
||||||
for (const ent of list) {
|
for (const ent of list) {
|
||||||
frag.appendChild(rowFor(ent, depth));
|
frag.appendChild(rowFor(ent, depth));
|
||||||
if (ent.type === 'dir' && !ent.ignored && expanded.has(ent.rel)) {
|
if (ent.type === 'dir' && expanded.has(ent.rel)) {
|
||||||
const kids = document.createElement('div');
|
const kids = document.createElement('div');
|
||||||
kids.className = 'tree-children';
|
kids.className = 'tree-children';
|
||||||
frag.appendChild(kids);
|
frag.appendChild(kids);
|
||||||
renderDirInto(kids, ent.rel, depth + 1).catch(function () {}); // 异步填充子层
|
renderDirInto(kids, ent.rel, depth + 1, ent.mtimeMs).catch(function () {}); // 异步填充子层
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (data.capped) tip(frag, '仅显示前 ' + list.length + ' 项(共 ' + data.total + ' 项)', 'tree-more');
|
if (data.capped) tip(frag, '仅显示前 ' + list.length + ' 项(共 ' + data.total + ' 项)', 'tree-more');
|
||||||
@@ -232,7 +241,7 @@
|
|||||||
const body = $('tree-body');
|
const body = $('tree-body');
|
||||||
if (!body) return [];
|
if (!body) return [];
|
||||||
return Array.from(body.querySelectorAll('.tree-row')).filter(function (r) {
|
return Array.from(body.querySelectorAll('.tree-row')).filter(function (r) {
|
||||||
return !r.classList.contains('is-ignored') && r.dataset.type !== 'link';
|
return r.dataset.type !== 'link';
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -369,9 +378,10 @@
|
|||||||
if (a === 'download') { if (typeof downloadFile === 'function') downloadFile(rel); }
|
if (a === 'download') { if (typeof downloadFile === 'function') downloadFile(rel); }
|
||||||
else if (a === 'delete') deleteNode(rel, isDir);
|
else if (a === 'delete') deleteNode(rel, isDir);
|
||||||
else if (a === 'reveal') localAction('reveal', rel);
|
else if (a === 'reveal') localAction('reveal', rel);
|
||||||
|
else if (a === 'at') insertPathRef(rel, isDir);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (row.classList.contains('is-ignored') || row.dataset.type === 'link') return;
|
if (row.dataset.type === 'link') return;
|
||||||
if (isDir) {
|
if (isDir) {
|
||||||
if (expanded.has(rel)) expanded.delete(rel); else expanded.add(rel);
|
if (expanded.has(rel)) expanded.delete(rel); else expanded.add(rel);
|
||||||
renderBody();
|
renderBody();
|
||||||
@@ -382,7 +392,32 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// @ 引用:把相对路径插到对话框光标处。插的是纯相对路径,不带 @ 前缀——
|
||||||
|
// @<会话id>/<rel> 是跨会话只读路径的语法(resolvePastPath),带上会被当成会话 id 而报错。
|
||||||
|
// 相对路径正是 read_file / list_directory 直接认的形态。
|
||||||
|
function insertPathRef(rel, isDir) {
|
||||||
|
const ta = $('msg-input');
|
||||||
|
if (!ta || !rel) return;
|
||||||
|
const txt = isDir ? rel + '/' : rel;
|
||||||
|
const s = ta.selectionStart == null ? ta.value.length : ta.selectionStart;
|
||||||
|
const e = ta.selectionEnd == null ? s : ta.selectionEnd;
|
||||||
|
const before = ta.value.slice(0, s);
|
||||||
|
const after = ta.value.slice(e);
|
||||||
|
// 前后补空格:粘在已有文字上会让路径和句子糊成一串,AI 切不开。
|
||||||
|
// 末尾(光标后无内容)也补一个,光标落在空格之后,接着打字不会和路径粘连。
|
||||||
|
const lead = before && !/\s$/.test(before) ? ' ' : '';
|
||||||
|
const tail = after ? (/^\s/.test(after) ? '' : ' ') : ' ';
|
||||||
|
ta.value = before + lead + txt + tail + after;
|
||||||
|
// 光标落在「路径 + 尾部空格」之后:末尾插入时继续打字不会和路径粘连(空格真起作用),
|
||||||
|
// 开头/中间插入时也停在插入块之后,与原文自然隔开。
|
||||||
|
const pos = (before + lead + txt + tail).length;
|
||||||
|
ta.focus();
|
||||||
|
try { ta.setSelectionRange(pos, pos); } catch (_) { /* 部分环境不支持,光标位置不强求 */ }
|
||||||
|
ta.dispatchEvent(new Event('input', { bubbles: true })); // 发送按钮状态 / 自动高度靠它跟上
|
||||||
|
}
|
||||||
|
|
||||||
// local 能力探测结果回来后才把「在 Finder/终端中打开」露出来(服务器形态永远隐藏)
|
// local 能力探测结果回来后才把「在 Finder/终端中打开」露出来(服务器形态永远隐藏)
|
||||||
|
|
||||||
function syncLocalButtons() {
|
function syncLocalButtons() {
|
||||||
const rv = $('tree-reveal'), tm = $('tree-terminal');
|
const rv = $('tree-reveal'), tm = $('tree-terminal');
|
||||||
if (rv) rv.classList.toggle('hidden', !localCapable);
|
if (rv) rv.classList.toggle('hidden', !localCapable);
|
||||||
@@ -460,7 +495,10 @@
|
|||||||
// 侧栏底部「文件树」图标 → 切到这个面板(由 files.js 的 setDrawerPane 调用)。
|
// 侧栏底部「文件树」图标 → 切到这个面板(由 files.js 的 setDrawerPane 调用)。
|
||||||
window.showFileTree = function () {
|
window.showFileTree = function () {
|
||||||
ensureShell();
|
ensureShell();
|
||||||
invalidate(true); // 切回面板一律重拉已展开的目录,不拿上次的缓存糊弄(后台只标脏的也在这里补上)
|
// 缓存还在就直接用:同一会话里反复开关面板,不该把已展开的目录全部重拉一遍
|
||||||
|
// (展开 N 层就是 N 轮请求,移动网络下能到 1-2 秒)。文件真变了有 reloadFileTree 兜底,
|
||||||
|
// 它在一轮跑完 / 回前台 / 断线重连时会把已展开的层重新拉一遍。
|
||||||
|
if (!cache.size) invalidate(true);
|
||||||
renderBody();
|
renderBody();
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -158,10 +158,10 @@
|
|||||||
return fileSelected.has(p) || isPathInDirSel(p);
|
return fileSelected.has(p) || isPathInDirSel(p);
|
||||||
}
|
}
|
||||||
// 目录节点内所有文件的相对路径(递归)
|
// 目录节点内所有文件的相对路径(递归)
|
||||||
|
// 当前层能拿到的文件(懒加载只拉这一层,子目录内容没有;
|
||||||
|
// 目录整体勾选走 dirSelKey,zip 打包由后端 collectZipEntries 递归)
|
||||||
function filesUnderDir(node) {
|
function filesUnderDir(node) {
|
||||||
let out = node.files.map(f => f.filename);
|
return node ? node.files.map(f => f.filename) : [];
|
||||||
for (const d of node.dirs.values()) out = out.concat(filesUnderDir(d));
|
|
||||||
return out;
|
|
||||||
}
|
}
|
||||||
// 全选的作用域 = 当前浏览目录下的全部文件(递归含其子文件夹,等价于逐个勾选这些文件夹行)。
|
// 全选的作用域 = 当前浏览目录下的全部文件(递归含其子文件夹,等价于逐个勾选这些文件夹行)。
|
||||||
// 不能再用全任务树的扁平列表:在子文件夹里点全选会把根下其它文件也选上,批量删除会清空整个任务目录。
|
// 不能再用全任务树的扁平列表:在子文件夹里点全选会把根下其它文件也选上,批量删除会清空整个任务目录。
|
||||||
@@ -297,31 +297,28 @@
|
|||||||
// 扁平文件列表 → 树节点 { name, path, dirs: Map, files: [] }
|
// 扁平文件列表 → 树节点 { name, path, dirs: Map, files: [] }
|
||||||
// 目录标记行(?dirs=1:filename 以 '/' 结尾 + dir:true)只沿途铺设路径节点、不入任何 files[],
|
// 目录标记行(?dirs=1:filename 以 '/' 结尾 + dir:true)只沿途铺设路径节点、不入任何 files[],
|
||||||
// 不含文件的空夹子因此也能渲染;与同名文件路径铺出的节点经 dirs Map 天然去重。
|
// 不含文件的空夹子因此也能渲染;与同名文件路径铺出的节点经 dirs Map 天然去重。
|
||||||
function buildFilesTree(files) {
|
// 把 /tree 返回的单层 entries 变成渲染用节点(子目录只留空 Map,进入时才拉)
|
||||||
const root = { name: '', path: '', dirs: new Map(), files: [] };
|
function buildNodeFromEntries(dir, entries) {
|
||||||
for (const f of files) {
|
const node = { name: dir.split('/').pop() || '', path: dir, dirs: new Map(), files: [] };
|
||||||
const isDir = f.dir === true || /\/$/.test(String(f.filename));
|
for (const e of entries) {
|
||||||
const name = isDir ? String(f.filename).replace(/\/+$/, '') : String(f.filename);
|
if (e.type === 'dir') {
|
||||||
if (!name) continue;
|
node.dirs.set(e.name, { name: e.name, path: e.rel, dirs: new Map(), files: [], mtime: e.mtimeMs });
|
||||||
const segs = name.split('/');
|
} else if (e.type === 'file') {
|
||||||
let node = root, rel = '';
|
node.files.push({ filename: e.rel, size: e.size, mtime: e.mtimeMs, ctime: e.mtimeMs });
|
||||||
const dirDepth = isDir ? segs.length : segs.length - 1; // 文件:末段是文件名;目录:全是路径段
|
|
||||||
for (let i = 0; i < dirDepth; i++) {
|
|
||||||
const seg = segs[i];
|
|
||||||
rel = rel ? rel + '/' + seg : seg;
|
|
||||||
if (!node.dirs.has(seg)) node.dirs.set(seg, { name: seg, path: rel, dirs: new Map(), files: [] });
|
|
||||||
node = node.dirs.get(seg);
|
|
||||||
}
|
}
|
||||||
if (!isDir) node.files.push(f);
|
|
||||||
}
|
}
|
||||||
return root;
|
return node;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 目录(含子目录)内文件总数,用于目录头计数
|
// 文件/目录时间:统一「年/月/日 时:分」。全局 fmtTime 对今天只给时分(聊天消息那种场景),
|
||||||
function countDirFiles(node) {
|
// 文件列表要能一眼看出新旧,所以固定带日期。
|
||||||
let n = node.files.length;
|
function fmtFileTime(ts) {
|
||||||
for (const d of node.dirs.values()) n += countDirFiles(d);
|
if (!ts) return '';
|
||||||
return n;
|
const d = new Date(ts);
|
||||||
|
if (isNaN(d.getTime())) return '';
|
||||||
|
const p = n => String(n).padStart(2, '0');
|
||||||
|
return d.getFullYear() + '/' + p(d.getMonth() + 1) + '/' + p(d.getDate())
|
||||||
|
+ ' ' + p(d.getHours()) + ':' + p(d.getMinutes());
|
||||||
}
|
}
|
||||||
|
|
||||||
function fileRowHtml(f) {
|
function fileRowHtml(f) {
|
||||||
@@ -329,10 +326,10 @@
|
|||||||
const low = f.filename.toLowerCase();
|
const low = f.filename.toLowerCase();
|
||||||
const fsPv = /\.(md|txt|html?|pdf|png|jpe?g|gif|webp|svg|docx|xlsx|pptx|csv|tsv|json|jsonl|xml|yml|yaml|toml|ini|conf|cfg|properties|env|log|py|pyw|js|mjs|cjs|ts|tsx|jsx|java|kt|c|h|cpp|hpp|cc|cs|go|rs|rb|php|swift|sh|bash|zsh|bat|ps1|sql|lua|r|dart|vue|css|less|scss|srt|vtt)$/.test(low);
|
const fsPv = /\.(md|txt|html?|pdf|png|jpe?g|gif|webp|svg|docx|xlsx|pptx|csv|tsv|json|jsonl|xml|yml|yaml|toml|ini|conf|cfg|properties|env|log|py|pyw|js|mjs|cjs|ts|tsx|jsx|java|kt|c|h|cpp|hpp|cc|cs|go|rs|rb|php|swift|sh|bash|zsh|bat|ps1|sql|lua|r|dart|vue|css|less|scss|srt|vtt)$/.test(low);
|
||||||
const ico = fsPv
|
const ico = fsPv
|
||||||
? '<svg class="file-ico eye" viewBox="0 0 24 24" aria-label="可预览"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path><circle cx="12" cy="12" r="3"></circle></svg>'
|
? '<svg class="file-ico eye" viewBox="0 0 24 24" aria-label="可预览"><use href="#i-eye"/></svg>'
|
||||||
: '<svg class="file-ico doc" viewBox="0 0 24 24" aria-label="可下载"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><polyline points="14 2 14 8 20 8"></polyline></svg>';
|
: '<svg class="file-ico doc" viewBox="0 0 24 24" aria-label="可下载"><use href="#i-file-doc"/></svg>';
|
||||||
const name = esc(String(f.filename).split('/').pop() || f.filename);
|
const name = esc(String(f.filename).split('/').pop() || f.filename);
|
||||||
const ftime = fmtTime(f.mtime || f.ctime);
|
const ftime = fmtFileTime(f.mtime || f.ctime);
|
||||||
const sel = isFileEffectivelySelected(f.filename);
|
const sel = isFileEffectivelySelected(f.filename);
|
||||||
return '<div class="file-row clickable' + (sel ? ' selected' : '') + '" data-path="' + esc(f.filename) + '" data-preview="' + (fsPv ? '1' : '0') + '" data-size="' + esc(fmtSize(f.size)) + '">' +
|
return '<div class="file-row clickable' + (sel ? ' selected' : '') + '" data-path="' + esc(f.filename) + '" data-preview="' + (fsPv ? '1' : '0') + '" data-size="' + esc(fmtSize(f.size)) + '">' +
|
||||||
'<span class="file-check" role="checkbox" aria-checked="' + (sel ? 'true' : 'false') + '" aria-label="选择"></span>' +
|
'<span class="file-check" role="checkbox" aria-checked="' + (sel ? 'true' : 'false') + '" aria-label="选择"></span>' +
|
||||||
@@ -346,29 +343,23 @@
|
|||||||
|
|
||||||
// 目录行(带勾选框):整个文件夹作为一个选中项(下载时后端打包成 zip);
|
// 目录行(带勾选框):整个文件夹作为一个选中项(下载时后端打包成 zip);
|
||||||
// 点行其余区域进入该目录(单层列表,不再有折叠/展开)。
|
// 点行其余区域进入该目录(单层列表,不再有折叠/展开)。
|
||||||
|
// 懒加载下不知道子目录内容,勾选态只看这一行自己是否被整体勾选;右侧显示修改时间,和文件行一致。
|
||||||
function dirRowHtml(node) {
|
function dirRowHtml(node) {
|
||||||
const under = filesUnderDir(node);
|
const checked = fileSelected.has(dirSelKey(node.path));
|
||||||
const checked = fileSelected.has(dirSelKey(node.path)) ||
|
const dtime = fmtFileTime(node.mtime);
|
||||||
(under.length > 0 && under.every(isFileEffectivelySelected));
|
|
||||||
return '<div class="file-dir-head' + (checked ? ' selected' : '') + '" data-dir="' + esc(node.path) + '" role="button">' +
|
return '<div class="file-dir-head' + (checked ? ' selected' : '') + '" data-dir="' + esc(node.path) + '" role="button">' +
|
||||||
'<span class="file-check" role="checkbox" aria-checked="' + (checked ? 'true' : 'false') + '" aria-label="选择文件夹"></span>' +
|
'<span class="file-check" role="checkbox" aria-checked="' + (checked ? 'true' : 'false') + '" aria-label="选择文件夹"></span>' +
|
||||||
'<svg class="file-dir-ico" viewBox="0 0 24 24"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"></path></svg>' +
|
'<svg class="file-dir-ico" viewBox="0 0 24 24"><use href="#i-folder-c"/></svg>' +
|
||||||
'<span class="file-dir-name">' + esc(node.name) + '</span>' +
|
'<span class="file-dir-name">' + esc(node.name) + '</span>' +
|
||||||
'<span class="file-dir-count">' + countDirFiles(node) + ' 个文件</span>' +
|
(dtime ? '<span class="file-dir-time">' + dtime + '</span>' : '') +
|
||||||
'<svg class="file-dir-go" viewBox="0 0 24 24"><polyline points="9 18 15 12 9 6"></polyline></svg>' +
|
'<svg class="file-dir-go" viewBox="0 0 24 24"><use href="#i-chevron-right"/></svg>' +
|
||||||
'</div>';
|
'</div>';
|
||||||
}
|
}
|
||||||
|
|
||||||
// 按相对路径取树节点('' = 根);路径不存在(如删除后重拉)返回 null
|
// 懒加载下只有当前浏览目录的节点('' = 根);其它路径没有数据
|
||||||
function filesNodeAt(path) {
|
function filesNodeAt(path) {
|
||||||
let node = filesTreeRoot;
|
if (!filesTreeRoot) return null;
|
||||||
if (!node) return null;
|
return (path || '') === filesCurDir ? filesTreeRoot : null;
|
||||||
if (!path) return node;
|
|
||||||
for (const seg of String(path).split('/')) {
|
|
||||||
node = node.dirs.get(seg);
|
|
||||||
if (!node) return null;
|
|
||||||
}
|
|
||||||
return node;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 渲染当前目录:顶部面包屑(根目录(home) › a › b,点任意节点回跳)+ 单层列表(目录在前、文件在后)。
|
// 渲染当前目录:顶部面包屑(根目录(home) › a › b,点任意节点回跳)+ 单层列表(目录在前、文件在后)。
|
||||||
@@ -380,13 +371,13 @@
|
|||||||
if (!node) { filesCurDir = ''; node = filesNodeAt(''); } // 当前目录已被删除 → 退回根
|
if (!node) { filesCurDir = ''; node = filesNodeAt(''); } // 当前目录已被删除 → 退回根
|
||||||
const sizeEl = $('files-panel-size');
|
const sizeEl = $('files-panel-size');
|
||||||
if (!node) { el.innerHTML = ''; if (sizeEl) sizeEl.textContent = ''; return; }
|
if (!node) { el.innerHTML = ''; if (sizeEl) sizeEl.textContent = ''; return; }
|
||||||
// 标题旁总大小:按未过滤的聚合表取当前目录递归总量(关彩蛋时服务端不返回 dot 项;开彩蛋时含 .imgcache/.tmp/.venv 全计)
|
// 标题旁总大小:只算当前层文件(子目录的递归大小要额外扫全树,懒加载拿不到)
|
||||||
if (sizeEl) {
|
if (sizeEl) {
|
||||||
const total = filesDirSizes.get(filesCurDir) || 0;
|
const total = filesDirSizes.get(filesCurDir) || 0;
|
||||||
sizeEl.textContent = total > 0 ? fmtSize(total) : '';
|
sizeEl.textContent = total > 0 ? fmtSize(total) : '';
|
||||||
}
|
}
|
||||||
// 根节点:home 图标 + 「根目录」,比一个孤悬的「/」醒目得多;在根时它是当前层,纯文本不可点
|
// 根节点:home 图标 + 「根目录」,比一个孤悬的「/」醒目得多;在根时它是当前层,纯文本不可点
|
||||||
const homeIc = '<svg class="crumb-ic" viewBox="0 0 24 24"><path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path><polyline points="9 22 9 12 15 12 15 22"></polyline></svg>';
|
const homeIc = '<svg class="crumb-ic" viewBox="0 0 24 24"><use href="#i-home"/></svg>';
|
||||||
let html = filesCurDir
|
let html = filesCurDir
|
||||||
? '<span class="crumb" data-path="">' + homeIc + '根目录</span>'
|
? '<span class="crumb" data-path="">' + homeIc + '根目录</span>'
|
||||||
: '<span class="crumb cur">' + homeIc + '根目录</span>';
|
: '<span class="crumb cur">' + homeIc + '根目录</span>';
|
||||||
@@ -419,28 +410,18 @@
|
|||||||
filesTreeRoot = null;
|
filesTreeRoot = null;
|
||||||
updateFilesFooter();
|
updateFilesFooter();
|
||||||
try {
|
try {
|
||||||
// 彩蛋开启时后端连 dot 项一起列,且不再滤 .tmp/.venv(全量放出)
|
// 按目录懒加载:只拉当前这一层(/tree),不再全量递归。
|
||||||
|
// 之前一次拉全树,仓库级工作目录能到 1.4MB(10544 个文件,81% 在 node_modules)。
|
||||||
const hiddenQ = filesShowHidden ? '&hidden=1' : '';
|
const hiddenQ = filesShowHidden ? '&hidden=1' : '';
|
||||||
const files = await req('GET', '/api/sessions/' + state.sessionId + '/files?dirs=1' + hiddenQ);
|
const data = await req('GET', '/api/sessions/' + state.sessionId + '/tree?dir='
|
||||||
// 会话级 .tmp(executor 的共享 /tmp 落盘处)与 .venv(Python 虚拟环境)不属于任务产物:默认隐藏(老后端兼容兑底;新版关彩蛋时服务端已不返回 dot 项)
|
+ encodeURIComponent(filesCurDir) + hiddenQ);
|
||||||
const shown = filesShowHidden ? files : files.filter(f => !/^(\.tmp|\.venv)(\/|$)/.test(String(f.filename)));
|
const entries = (data && data.entries) || [];
|
||||||
// 重建目录树后只渲染当前目录这一层(后端已按时间倒序,组内再排一次防旧排序缓存)
|
filesTreeRoot = buildNodeFromEntries(filesCurDir, entries);
|
||||||
filesTreeRoot = buildFilesTree(shown);
|
// 标题旁总大小:只统计当前层文件(子目录的递归大小要额外扫全树,懒加载拿不到)
|
||||||
// 总大小按原始列表(含 .tmp/.venv)聚合:目录标记行无字节量跳过;文件把 size 记到每一级祖先目录(根 = '')
|
let total = 0;
|
||||||
filesDirSizes = new Map([['', 0]]);
|
for (const f of filesTreeRoot.files) total += Number(f.size) || 0;
|
||||||
for (const f of files) {
|
filesDirSizes = new Map([[filesCurDir, total]]);
|
||||||
if (f.dir === true || /\/$/.test(String(f.filename))) continue;
|
if (data && data.capped) toast('目录条目过多,仅显示前 ' + entries.length + ' 项');
|
||||||
const sz = Number(f.size) || 0;
|
|
||||||
if (!sz) continue;
|
|
||||||
filesDirSizes.set('', (filesDirSizes.get('') || 0) + sz);
|
|
||||||
const segs = String(f.filename).split('/');
|
|
||||||
segs.pop(); // 末段是文件名,其余是祖先目录
|
|
||||||
let acc = '';
|
|
||||||
for (const seg of segs) {
|
|
||||||
acc = acc ? acc + '/' + seg : seg;
|
|
||||||
filesDirSizes.set(acc, (filesDirSizes.get(acc) || 0) + sz);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
renderFilesDir(); // filesCurDir 失效时自动退回根目录
|
renderFilesDir(); // filesCurDir 失效时自动退回根目录
|
||||||
// 重新渲染后刷新底部计数与按钮状态
|
// 重新渲染后刷新底部计数与按钮状态
|
||||||
updateFilesFooter();
|
updateFilesFooter();
|
||||||
@@ -543,8 +524,7 @@
|
|||||||
if (!dp || !state.sessionId) return;
|
if (!dp || !state.sessionId) return;
|
||||||
if (e.target.closest('.file-check')) { toggleDirSelect(dp); return; }
|
if (e.target.closest('.file-check')) { toggleDirSelect(dp); return; }
|
||||||
filesCurDir = dp;
|
filesCurDir = dp;
|
||||||
renderFilesDir();
|
loadFiles(); // 懒加载:进哪层拉哪层(renderFilesDir / updateFilesFooter 在它内部调)
|
||||||
updateFilesFooter(); // 全选作用域随浏览目录变化,刷新底部勾选态
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const row = e.target.closest('.file-row');
|
const row = e.target.closest('.file-row');
|
||||||
@@ -594,8 +574,7 @@
|
|||||||
const c = e.target.closest('.crumb[data-path]');
|
const c = e.target.closest('.crumb[data-path]');
|
||||||
if (!c) return;
|
if (!c) return;
|
||||||
filesCurDir = c.dataset.path;
|
filesCurDir = c.dataset.path;
|
||||||
renderFilesDir();
|
loadFiles(); // 同上:面包屑回跳也按目录重拉
|
||||||
updateFilesFooter(); // 同上:面包屑回跳也重算全选态
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// 彩蛋:点面板标题旁的总大小文本 = 切换隐藏文件(dot 项含 .tmp/.venv)显隐。
|
// 彩蛋:点面板标题旁的总大小文本 = 切换隐藏文件(dot 项含 .tmp/.venv)显隐。
|
||||||
@@ -773,8 +752,8 @@
|
|||||||
function uploadIconSvg(name) {
|
function uploadIconSvg(name) {
|
||||||
// 与文件面板同款图标语言:图片用图、其余用文档
|
// 与文件面板同款图标语言:图片用图、其余用文档
|
||||||
return /\.(png|jpe?g|gif|webp|bmp|svg)$/i.test(name || '')
|
return /\.(png|jpe?g|gif|webp|bmp|svg)$/i.test(name || '')
|
||||||
? '<svg class="ic" viewBox="0 0 24 24"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect><circle cx="8.5" cy="8.5" r="1.5"></circle><polyline points="21 15 16 10 5 21"></polyline></svg>'
|
? '<svg class="ic" viewBox="0 0 24 24"><use href="#i-image-b"/></svg>'
|
||||||
: '<svg class="ic" viewBox="0 0 24 24"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><polyline points="14 2 14 8 20 8"></polyline></svg>';
|
: '<svg class="ic" viewBox="0 0 24 24"><use href="#i-file-doc"/></svg>';
|
||||||
}
|
}
|
||||||
function addUploadCard(file) {
|
function addUploadCard(file) {
|
||||||
const row = $('up-cards');
|
const row = $('up-cards');
|
||||||
@@ -789,7 +768,7 @@
|
|||||||
'<div class="up-meta">' + uploadTypeLabel(file.name) + ' · ' + fmtSize(file.size) + '</div>' +
|
'<div class="up-meta">' + uploadTypeLabel(file.name) + ' · ' + fmtSize(file.size) + '</div>' +
|
||||||
'</div>' +
|
'</div>' +
|
||||||
'<button class="up-x hidden" title="不再随消息告知该文件" aria-label="移除卡片">' +
|
'<button class="up-x hidden" title="不再随消息告知该文件" aria-label="移除卡片">' +
|
||||||
'<svg class="ic" viewBox="0 0 24 24"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>' +
|
'<svg class="ic" viewBox="0 0 24 24"><use href="#i-x-line-b"/></svg>' +
|
||||||
'</button>' +
|
'</button>' +
|
||||||
'<div class="up-mask"><span class="up-pct">0%</span></div>';
|
'<div class="up-mask"><span class="up-pct">0%</span></div>';
|
||||||
const mask = card.querySelector('.up-mask');
|
const mask = card.querySelector('.up-mask');
|
||||||
@@ -1058,7 +1037,7 @@
|
|||||||
row.innerHTML = state.attachments.map((f, i) =>
|
row.innerHTML = state.attachments.map((f, i) =>
|
||||||
'<span class="attach-chip"><span class="name">' + esc(f.name) + '</span>' +
|
'<span class="attach-chip"><span class="name">' + esc(f.name) + '</span>' +
|
||||||
'<button class="rm" data-i="' + i + '" aria-label="移除附件">' +
|
'<button class="rm" data-i="' + i + '" aria-label="移除附件">' +
|
||||||
'<svg class="ic sm" viewBox="0 0 24 24"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>' +
|
'<svg class="ic sm" viewBox="0 0 24 24"><use href="#i-x-line-b"/></svg>' +
|
||||||
'</button></span>').join('');
|
'</button></span>').join('');
|
||||||
}
|
}
|
||||||
$('attach-chips').addEventListener('click', e => {
|
$('attach-chips').addEventListener('click', e => {
|
||||||
|
|||||||
@@ -0,0 +1,116 @@
|
|||||||
|
// 数学公式渲染(KaTeX 本地化,vendor/katex/)。
|
||||||
|
// 所有 markdown 入口(聊天气泡 / md 文件预览 / 流式增量)都走 core.js 的 mdHtml(),
|
||||||
|
// 公式处理收在这一个文件里,不散落到各处。
|
||||||
|
//
|
||||||
|
// 支持:
|
||||||
|
// $$...$$ 块级(可换行)
|
||||||
|
// $...$ 行内($ 后不能是空白、前不能是数字/字母,避免「$5 ... $6」被当公式)
|
||||||
|
//
|
||||||
|
// 实现方式:占位符往返,而不是 marked 扩展。
|
||||||
|
// 1) markdown 解析前,把公式抠成 @@MATHn@@ 占位(跳过围栏代码与行内代码)
|
||||||
|
// 2) 交给 marked 正常解析
|
||||||
|
// 3) 输出 HTML 里把占位换回 KaTeX 渲染结果
|
||||||
|
// 这样公式里的 * _ \ { } 不会被 marked 当成强调/转义吃掉。
|
||||||
|
|
||||||
|
const MATH_PH = /@@MATH(\d+)@@/g;
|
||||||
|
|
||||||
|
// 从 markdown 源里抠出公式,返回 { md, store }
|
||||||
|
function mathExtract(src) {
|
||||||
|
const text = String(src || '');
|
||||||
|
const store = [];
|
||||||
|
let out = '';
|
||||||
|
let i = 0;
|
||||||
|
while (i < text.length) {
|
||||||
|
// 围栏代码块整段跳过(三个反引号)
|
||||||
|
if (text.startsWith('```', i)) {
|
||||||
|
const end = text.indexOf('```', i + 3);
|
||||||
|
const stop = end < 0 ? text.length : end + 3;
|
||||||
|
out += text.slice(i, stop);
|
||||||
|
i = stop;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// 行内代码跳过
|
||||||
|
if (text[i] === '`') {
|
||||||
|
const end = text.indexOf('`', i + 1);
|
||||||
|
if (end > i) {
|
||||||
|
out += text.slice(i, end + 1);
|
||||||
|
i = end + 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 块级 $$...$$
|
||||||
|
if (text.startsWith('$$', i)) {
|
||||||
|
const end = text.indexOf('$$', i + 2);
|
||||||
|
if (end > i + 2) {
|
||||||
|
const latex = text.slice(i + 2, end).trim();
|
||||||
|
if (latex) {
|
||||||
|
store.push({ latex: latex, display: true });
|
||||||
|
out += '@@MATH' + (store.length - 1) + '@@';
|
||||||
|
i = end + 2;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 行内 $...$
|
||||||
|
if (text[i] === '$') {
|
||||||
|
const m = /^\$(?!\s)((?:\\.|[^$\\\n])+?)(?<!\s)\$/.exec(text.slice(i));
|
||||||
|
if (m) {
|
||||||
|
const before = i > 0 ? text[i - 1] : '';
|
||||||
|
const after = text[i + m[0].length] || '';
|
||||||
|
// 前后紧邻字母/数字时不当公式:$5 和 $6、a$b$c 之类
|
||||||
|
if (!/[0-9A-Za-z]/.test(before) && !/[0-9A-Za-z]/.test(after)) {
|
||||||
|
store.push({ latex: m[1], display: false });
|
||||||
|
out += '@@MATH' + (store.length - 1) + '@@';
|
||||||
|
i += m[0].length;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out += text[i];
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
return { md: out, store: store };
|
||||||
|
}
|
||||||
|
|
||||||
|
function mathEsc(s) {
|
||||||
|
return String(s == null ? '' : s).replace(/[&<>"]/g, function (c) {
|
||||||
|
return { '&': '&', '<': '<', '>': '>', '"': '"' }[c];
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 单个公式 → HTML。KaTeX 不存在或 LaTeX 有错时原样吐回,用户能看见哪里写错了。
|
||||||
|
function mathRenderOne(latex, display) {
|
||||||
|
const wrap = display ? '$$' : '$';
|
||||||
|
if (typeof katex === 'undefined') {
|
||||||
|
return '<span class="math-fallback">' + wrap + mathEsc(latex) + wrap + '</span>';
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const html = katex.renderToString(latex, {
|
||||||
|
displayMode: display,
|
||||||
|
throwOnError: false,
|
||||||
|
output: 'html',
|
||||||
|
strict: false,
|
||||||
|
});
|
||||||
|
// 块级公式自己占一行;行内公式保持内联
|
||||||
|
return display ? '<span class="math-block">' + html + '</span>' : '<span class="math-inline">' + html + '</span>';
|
||||||
|
} catch (e) {
|
||||||
|
return '<span class="math-error" title="' + mathEsc(String((e && e.message) || e)) + '">' +
|
||||||
|
wrap + mathEsc(latex) + wrap + '</span>';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 把 HTML 里的占位换回渲染结果
|
||||||
|
function mathExpand(html, store) {
|
||||||
|
if (!store || !store.length) return html;
|
||||||
|
return String(html || '').replace(MATH_PH, function (all, idx) {
|
||||||
|
const item = store[Number(idx)];
|
||||||
|
return item ? mathRenderOne(item.latex, item.display) : all;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 一步到位:markdown → 含公式的 HTML。markedRef 由调用方传入(core.js 里的全局 marked)
|
||||||
|
function mdParseWithMath(text, markedRef) {
|
||||||
|
const r = mathExtract(text);
|
||||||
|
const html = markedRef.parse(r.md);
|
||||||
|
return mathExpand(html, r.store);
|
||||||
|
}
|
||||||
+144
-32
@@ -15,6 +15,59 @@ const PV_PLAIN = /\.(txt|log)$/i;
|
|||||||
// 常见代码/配置/数据文本扩展名;无扩展名的文件(Dockerfile/LICENSE 等)也按文本尝试,二进制嗅探兜底
|
// 常见代码/配置/数据文本扩展名;无扩展名的文件(Dockerfile/LICENSE 等)也按文本尝试,二进制嗅探兜底
|
||||||
const PV_TEXT = /\.(md|markdown|txt|log|csv|tsv|json|jsonl|xml|yml|yaml|toml|ini|conf|cfg|properties|env|py|pyw|js|mjs|cjs|ts|tsx|jsx|java|kt|c|h|cpp|hpp|cc|cs|go|rs|rb|php|swift|sh|bash|zsh|bat|ps1|sql|lua|r|dart|vue|css|less|scss|srt|vtt)$/i;
|
const PV_TEXT = /\.(md|markdown|txt|log|csv|tsv|json|jsonl|xml|yml|yaml|toml|ini|conf|cfg|properties|env|py|pyw|js|mjs|cjs|ts|tsx|jsx|java|kt|c|h|cpp|hpp|cc|cs|go|rs|rb|php|swift|sh|bash|zsh|bat|ps1|sql|lua|r|dart|vue|css|less|scss|srt|vtt)$/i;
|
||||||
const PV_TEXT_MAX = 512 * 1024; // 文本预览截断阈值(字符),超出提示下载看全文
|
const PV_TEXT_MAX = 512 * 1024; // 文本预览截断阈值(字符),超出提示下载看全文
|
||||||
|
const PV_CODE_MAX = 5000; // 代码预览最多逐行渲染的行数:行号要逐行建节点,几万行会把面板拖死
|
||||||
|
// 扩展名 → Prism 语言 id。只映射打包进来的语言(见 vendor/prism.min.js),命中不了就当纯文本
|
||||||
|
const PV_LANG = {
|
||||||
|
js: 'javascript', mjs: 'javascript', cjs: 'javascript', jsx: 'jsx',
|
||||||
|
ts: 'typescript', mts: 'typescript', cts: 'typescript', tsx: 'tsx',
|
||||||
|
json: 'json', jsonl: 'json', json5: 'json',
|
||||||
|
yml: 'yaml', yaml: 'yaml',
|
||||||
|
sh: 'bash', bash: 'bash', zsh: 'bash', ksh: 'bash', env: 'bash',
|
||||||
|
py: 'python', pyw: 'python',
|
||||||
|
go: 'go', rs: 'rust', java: 'java',
|
||||||
|
c: 'c', h: 'c', cpp: 'cpp', hpp: 'cpp', cc: 'cpp', cxx: 'cpp', hh: 'cpp',
|
||||||
|
sql: 'sql', css: 'css', wxss: 'css',
|
||||||
|
html: 'markup', htm: 'markup', xml: 'markup', svg: 'markup', vue: 'markup',
|
||||||
|
md: 'markdown', markdown: 'markdown',
|
||||||
|
toml: 'toml', ini: 'ini', conf: 'ini', cfg: 'ini', properties: 'ini',
|
||||||
|
diff: 'diff', patch: 'diff',
|
||||||
|
};
|
||||||
|
// 整块高亮;Prism 没加载、语言没打包、或抛异常都返回 null,调用方退回纯文本
|
||||||
|
function pvHighlightCode(text, name) {
|
||||||
|
if (typeof Prism === 'undefined' || !Prism.languages) return null;
|
||||||
|
const ext = (String(name).match(/\.([^.\\/]+)$/) || [])[1];
|
||||||
|
const lang = PV_LANG[String(ext || '').toLowerCase()];
|
||||||
|
const grammar = lang && Prism.languages[lang];
|
||||||
|
if (!grammar) return null;
|
||||||
|
try { return Prism.highlight(text, grammar, lang); } catch (_) { return null; }
|
||||||
|
}
|
||||||
|
// 把整块高亮 HTML 按行拆开:跨行的 <span> 在行尾补 </span>、下一行行首重开。
|
||||||
|
// 逐行调用 Prism.highlight 会把多行注释/三引号字符串切花,所以必须先整块高亮再拆。
|
||||||
|
// Prism 输出的文本已转义(< 等),不存在裸 '<',因此只匹配标签与换行就够了。
|
||||||
|
function pvSplitHighlighted(html) {
|
||||||
|
const out = [];
|
||||||
|
const stack = [];
|
||||||
|
let cur = '';
|
||||||
|
let last = 0;
|
||||||
|
const re = /(\n|<span\b[^>]*>|<\/span>)/g;
|
||||||
|
let m;
|
||||||
|
while ((m = re.exec(html))) {
|
||||||
|
cur += html.slice(last, m.index);
|
||||||
|
last = m.index + m[0].length;
|
||||||
|
if (m[0] === '\n') {
|
||||||
|
out.push(cur + '</span>'.repeat(stack.length));
|
||||||
|
cur = stack.join('');
|
||||||
|
} else if (m[0] === '</span>') {
|
||||||
|
stack.pop();
|
||||||
|
cur += '</span>';
|
||||||
|
} else {
|
||||||
|
stack.push(m[0]);
|
||||||
|
cur += m[0];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.push(cur + html.slice(last)); // 末尾无条件留一行:文本以 \n 结尾时最后是空行
|
||||||
|
return out;
|
||||||
|
}
|
||||||
const PV_SRC_MAX = 2 * 1024 * 1024; // 源码面板的显示上限,超过就只给前 2MB(大文件塞 pre 会卡)
|
const PV_SRC_MAX = 2 * 1024 * 1024; // 源码面板的显示上限,超过就只给前 2MB(大文件塞 pre 会卡)
|
||||||
let pvSeq = 0; // 预览序号:快速连点时旧请求不许再动 DOM
|
let pvSeq = 0; // 预览序号:快速连点时旧请求不许再动 DOM
|
||||||
// reload: 当前内容的"重新载入"动作(文本类无 iframe,按名重开);为 null 时回退到 reload iframe
|
// reload: 当前内容的"重新载入"动作(文本类无 iframe,按名重开);为 null 时回退到 reload iframe
|
||||||
@@ -97,7 +150,7 @@ function pvToggleSrc() {
|
|||||||
let text = pvState.source;
|
let text = pvState.source;
|
||||||
if (text.length > PV_SRC_MAX) text = text.slice(0, PV_SRC_MAX) + '\n\n…(源码较大,仅显示前 ' + Math.round(PV_SRC_MAX / 1024) + ' KB)';
|
if (text.length > PV_SRC_MAX) text = text.slice(0, PV_SRC_MAX) + '\n\n…(源码较大,仅显示前 ' + Math.round(PV_SRC_MAX / 1024) + ' KB)';
|
||||||
const pre = document.createElement('pre');
|
const pre = document.createElement('pre');
|
||||||
pre.className = 'pv-pre pv-src-pre'; // 代码类预览本身也是 .pv-pre,多一个类便于区分/定位
|
pre.className = 'pv-pre pv-src-pre'; // 源码面板:不加行号的原文(代码预览本身走 .pv-code)
|
||||||
pre.textContent = text; // 不用 innerHTML:源码里的标签必须当文本
|
pre.textContent = text; // 不用 innerHTML:源码里的标签必须当文本
|
||||||
pvState.srcPre = pre;
|
pvState.srcPre = pre;
|
||||||
document.getElementById('pv-body').appendChild(pre);
|
document.getElementById('pv-body').appendChild(pre);
|
||||||
@@ -113,6 +166,20 @@ function pvToggleSrc() {
|
|||||||
btn.setAttribute('aria-label', lbl);
|
btn.setAttribute('aria-label', lbl);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// md 里的围栏代码块上色:marked 输出 <pre><code class="language-xx">,命中 PV_LANG 才处理。
|
||||||
|
// highlightElement 会重写 code 的 innerHTML,复制按钮挂在父级 .code-wrap 上,不受影响。
|
||||||
|
function pvHighlightMdCode(root) {
|
||||||
|
if (typeof Prism === 'undefined' || !Prism.languages) return;
|
||||||
|
root.querySelectorAll('pre code').forEach((el) => {
|
||||||
|
if (el.dataset.hl) return; // 幂等:同一节点被重复装饰时不再处理
|
||||||
|
const m = /language-([\w-]+)/.exec(String(el.className || ''));
|
||||||
|
const lang = m && PV_LANG[m[1].toLowerCase()];
|
||||||
|
if (!lang || !Prism.languages[lang]) return;
|
||||||
|
el.dataset.hl = '1';
|
||||||
|
try { Prism.highlightElement(el); } catch (_) {}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
// 每次展示内容都过一遍:标题显示相对路径(子目录可见),右上角下载钮随文件走
|
// 每次展示内容都过一遍:标题显示相对路径(子目录可见),右上角下载钮随文件走
|
||||||
function pvHeader(name, sizeText) {
|
function pvHeader(name, sizeText) {
|
||||||
pvState.name = name;
|
pvState.name = name;
|
||||||
@@ -145,8 +212,7 @@ function pvInfoNode(name, sizeText, hint) {
|
|||||||
const box = document.createElement('div');
|
const box = document.createElement('div');
|
||||||
box.className = 'pv-none';
|
box.className = 'pv-none';
|
||||||
box.innerHTML =
|
box.innerHTML =
|
||||||
'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round">' +
|
'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"><use href="#i-file-doc"/></svg>' +
|
||||||
'<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><polyline points="14 2 14 8 20 8"></polyline></svg>' +
|
|
||||||
'<div class="nm"></div><div class="meta"></div><div class="hint"></div>';
|
'<div class="nm"></div><div class="meta"></div><div class="hint"></div>';
|
||||||
box.querySelector('.nm').textContent = String(name || '');
|
box.querySelector('.nm').textContent = String(name || '');
|
||||||
box.querySelector('.meta').textContent = sizeText ? sizeText : '';
|
box.querySelector('.meta').textContent = sizeText ? sizeText : '';
|
||||||
@@ -431,21 +497,69 @@ function pvCloseOverlayQuiet() { const fs = document.getElementById('fs-viewer')
|
|||||||
// 其余按 text/plain 原样打开——服务端文件响应一律 attachment,直接导航只会触发下载。
|
// 其余按 text/plain 原样打开——服务端文件响应一律 attachment,直接导航只会触发下载。
|
||||||
// md 里原样透传的 <script> 在面板(innerHTML)本就不执行,但 blob 文档会执行,故先剔除以保持一致。
|
// md 里原样透传的 <script> 在面板(innerHTML)本就不执行,但 blob 文档会执行,故先剔除以保持一致。
|
||||||
function pvMdDoc(html, name) {
|
function pvMdDoc(html, name) {
|
||||||
|
// KaTeX 样式表用根绝对路径引入:blob 文档的 base 是 blob:,相对路径找不到字体
|
||||||
const css =
|
const css =
|
||||||
'body{margin:0;padding:24px 32px 48px;max-width:900px;font:15px/1.7 -apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif;color:#1f2328;background:#fff}' +
|
'body{margin:0;padding:24px 32px 48px;max-width:900px;font:15px/1.7 -apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif;color:#1f2328;background:#fff}' +
|
||||||
'img{max-width:100%;height:auto}pre{background:#f6f8fa;padding:12px 14px;border-radius:8px;overflow:auto}' +
|
'img{max-width:100%;height:auto}pre{background:#f6f8fa;padding:12px 14px;border-radius:8px;overflow:auto}' +
|
||||||
'code{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:.92em}' +
|
'code{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:.92em}' +
|
||||||
'table{border-collapse:collapse}th,td{border:1px solid #d8dee4;padding:6px 10px}' +
|
'table{border-collapse:collapse}th,td{border:1px solid #d8dee4;padding:6px 10px}' +
|
||||||
'blockquote{margin:0;padding:0 14px;color:#57606a;border-left:3px solid #d8dee4}' +
|
'blockquote{margin:0;padding:0 14px;color:#57606a;border-left:3px solid #d8dee4}' +
|
||||||
'a{color:#0969da}';
|
'a{color:#0969da}' +
|
||||||
|
'.math-block{display:block;text-align:center;margin:14px 0;overflow-x:auto;overflow-y:hidden}';
|
||||||
const title = esc(String(name || '').split('/').pop() || '预览');
|
const title = esc(String(name || '').split('/').pop() || '预览');
|
||||||
|
const origin = (typeof location !== 'undefined' && location.origin) ? location.origin : '';
|
||||||
return '<!DOCTYPE html><html><head><meta charset="utf-8">' +
|
return '<!DOCTYPE html><html><head><meta charset="utf-8">' +
|
||||||
'<meta name="viewport" content="width=device-width,initial-scale=1">' +
|
'<meta name="viewport" content="width=device-width,initial-scale=1">' +
|
||||||
'<title>' + title + '</title><style>' + css + '</style></head><body>' +
|
'<title>' + title + '</title>' +
|
||||||
|
'<link rel="stylesheet" href="' + origin + '/vendor/katex/katex.min.css">' +
|
||||||
|
'<style>' + css + '</style></head><body>' +
|
||||||
html.replace(/<script\b[\s\S]*?(?:<\/script\s*>|$)/gi, '') + '</body></html>';
|
html.replace(/<script\b[\s\S]*?(?:<\/script\s*>|$)/gi, '') + '</body></html>';
|
||||||
}
|
}
|
||||||
function pvTextUrl(text) { return URL.createObjectURL(new Blob([text], { type: 'text/plain;charset=utf-8' })); }
|
function pvTextUrl(text) { return URL.createObjectURL(new Blob([text], { type: 'text/plain;charset=utf-8' })); }
|
||||||
|
|
||||||
|
// 代码/配置/数据渲染:行号 + Prism 着色。桌面(pvTextNode)与移动端(pvRenderLegacy)共用——
|
||||||
|
// 移动端原来只 esc 成纯文本,同一个文件在手机上没行号也没颜色。
|
||||||
|
function pvCodeNode(text, name) {
|
||||||
|
const frag = document.createDocumentFragment();
|
||||||
|
let bodyText = text;
|
||||||
|
if (text.length > PV_TEXT_MAX) {
|
||||||
|
bodyText = text.slice(0, PV_TEXT_MAX);
|
||||||
|
const tip = document.createElement('div');
|
||||||
|
tip.className = 'pv-trunc';
|
||||||
|
tip.textContent = '文件较大,仅预览前 ' + Math.round(PV_TEXT_MAX / 1024) + ' KB,完整内容请下载查看。';
|
||||||
|
frag.appendChild(tip);
|
||||||
|
}
|
||||||
|
// 逐行渲染以便左侧打行号(视觉同 Git 面板的 .vcs-line)。
|
||||||
|
// 超过 PV_CODE_MAX 行只渲染前段,剩下的交代一句——几万个逐行节点会让面板卡到没法滚。
|
||||||
|
const lines = bodyText.split('\n');
|
||||||
|
const total = lines.length;
|
||||||
|
const shown = total > PV_CODE_MAX ? lines.slice(0, PV_CODE_MAX) : lines;
|
||||||
|
const code = document.createElement('div');
|
||||||
|
code.className = 'pv-code';
|
||||||
|
code.style.setProperty('--nw', Math.max(2, String(shown.length).length) + 'ch'); // 行号列宽按最大行号位数
|
||||||
|
const rows = [];
|
||||||
|
const hl = pvHighlightCode(shown.join('\n'), name); // 整块高亮再按行拆,跨行 token 才不会花
|
||||||
|
const parts = hl ? pvSplitHighlighted(hl) : null;
|
||||||
|
const useHl = parts && parts.length === shown.length; // 行数对不上就退回纯文本,不让行号错位
|
||||||
|
for (let i = 0; i < shown.length; i++) {
|
||||||
|
// 行号交给 CSS counter(.pv-cl::before)生成:伪元素不进选区,复制不会把行号带走。
|
||||||
|
// 代码必须包在 .c 里:裸文本在 flex 容器里是匿名 flex 项,浏览器会折叠它的前导空白。
|
||||||
|
rows.push('<div class="pv-cl"><span class="c">' + (useHl ? parts[i] : esc(shown[i])) + '</span></div>');
|
||||||
|
}
|
||||||
|
code.innerHTML = rows.join('');
|
||||||
|
frag.appendChild(code);
|
||||||
|
if (total > PV_CODE_MAX) {
|
||||||
|
const tip2 = document.createElement('div');
|
||||||
|
tip2.className = 'pv-trunc';
|
||||||
|
tip2.textContent = '文件较大,仅显示前 ' + PV_CODE_MAX + ' 行(共 ' + total + ' 行),完整内容请下载查看。';
|
||||||
|
frag.appendChild(tip2);
|
||||||
|
}
|
||||||
|
const holder = document.createElement('div');
|
||||||
|
holder.className = 'pv-plain';
|
||||||
|
holder.appendChild(frag);
|
||||||
|
return holder;
|
||||||
|
}
|
||||||
|
|
||||||
// 桌面文本渲染:md 走气泡 markdown;txt/log 原文排版;代码/配置/数据等宽 pre;二进制嗅探回退占位卡
|
// 桌面文本渲染:md 走气泡 markdown;txt/log 原文排版;代码/配置/数据等宽 pre;二进制嗅探回退占位卡
|
||||||
async function pvTextNode(name, sizeText, r) {
|
async function pvTextNode(name, sizeText, r) {
|
||||||
const text = await r.text();
|
const text = await r.text();
|
||||||
@@ -460,6 +574,7 @@ async function pvTextNode(name, sizeText, r) {
|
|||||||
wrap.className = 'msg other';
|
wrap.className = 'msg other';
|
||||||
wrap.innerHTML = '<div class="' + cls + ' pv-doc">' + html + '</div>';
|
wrap.innerHTML = '<div class="' + cls + ' pv-doc">' + html + '</div>';
|
||||||
decorateCodePre(wrap);
|
decorateCodePre(wrap);
|
||||||
|
pvHighlightMdCode(wrap); // 围栏代码块上色(与代码预览同一套配色)
|
||||||
const n = wrap.firstChild;
|
const n = wrap.firstChild;
|
||||||
// q.fmt=false 表示 marked 不可用、面板就是原文排版:新窗口也按纯文本开,避免空白被折叠
|
// q.fmt=false 表示 marked 不可用、面板就是原文排版:新窗口也按纯文本开,避免空白被折叠
|
||||||
n.__tb = q.fmt
|
n.__tb = q.fmt
|
||||||
@@ -475,22 +590,7 @@ async function pvTextNode(name, sizeText, r) {
|
|||||||
const n = wrap.firstChild; n.__tb = { popup: true, url: pvTextUrl(text) }; n.__src = text;
|
const n = wrap.firstChild; n.__tb = { popup: true, url: pvTextUrl(text) }; n.__src = text;
|
||||||
return n;
|
return n;
|
||||||
}
|
}
|
||||||
const frag = document.createDocumentFragment();
|
const holder = pvCodeNode(text, name);
|
||||||
let bodyText = text;
|
|
||||||
if (text.length > PV_TEXT_MAX) {
|
|
||||||
bodyText = text.slice(0, PV_TEXT_MAX);
|
|
||||||
const tip = document.createElement('div');
|
|
||||||
tip.className = 'pv-trunc';
|
|
||||||
tip.textContent = '文件较大,仅预览前 ' + Math.round(PV_TEXT_MAX / 1024) + ' KB,完整内容请下载查看。';
|
|
||||||
frag.appendChild(tip);
|
|
||||||
}
|
|
||||||
const pre = document.createElement('pre');
|
|
||||||
pre.className = 'pv-pre';
|
|
||||||
pre.textContent = bodyText;
|
|
||||||
frag.appendChild(pre);
|
|
||||||
const holder = document.createElement('div');
|
|
||||||
holder.className = 'pv-plain';
|
|
||||||
holder.appendChild(frag);
|
|
||||||
holder.__tb = { popup: true, url: pvTextUrl(text) }; // 新窗口用全文,不受面板截断影响
|
holder.__tb = { popup: true, url: pvTextUrl(text) }; // 新窗口用全文,不受面板截断影响
|
||||||
holder.__src = text; // 源码面板同样给全文
|
holder.__src = text; // 源码面板同样给全文
|
||||||
return holder;
|
return holder;
|
||||||
@@ -534,19 +634,21 @@ async function pvRenderLegacy(name, r, my) {
|
|||||||
openImageViewer(u, name, g && g.list, g && g.at);
|
openImageViewer(u, name, g && g.list, g && g.at);
|
||||||
} else {
|
} else {
|
||||||
const text = await r.text();
|
const text = await r.text();
|
||||||
let cls = 'bubble-ai', html;
|
if (!PV_MD.test(name)) {
|
||||||
if (PV_MD.test(name)) {
|
// 代码/配置/数据:与桌面同一套行号 + Prism 着色(原来在手机上只是纯文本)
|
||||||
|
pvOverlayShow(pvCodeNode(text, name), { bar: true, name: name, source: text });
|
||||||
|
return;
|
||||||
|
}
|
||||||
const q = mdHtml(text);
|
const q = mdHtml(text);
|
||||||
html = q.html;
|
let cls = 'bubble-ai';
|
||||||
|
let html = q.html;
|
||||||
if (q.fmt) cls += ' md';
|
if (q.fmt) cls += ' md';
|
||||||
html = rewriteMdImageSrcs(html, name);
|
html = rewriteMdImageSrcs(html, name);
|
||||||
} else {
|
|
||||||
html = esc(text);
|
|
||||||
}
|
|
||||||
const wrap = document.createElement('div');
|
const wrap = document.createElement('div');
|
||||||
wrap.className = 'msg other';
|
wrap.className = 'msg other';
|
||||||
wrap.innerHTML = '<div class="' + cls + '">' + html + '</div>';
|
wrap.innerHTML = '<div class="' + cls + '">' + html + '</div>';
|
||||||
decorateCodePre(wrap);
|
decorateCodePre(wrap);
|
||||||
|
pvHighlightMdCode(wrap);
|
||||||
pvOverlayShow(wrap.firstChild, { bar: true, name: name, source: text }); // 全宽沉浸,eye/复制看原文
|
pvOverlayShow(wrap.firstChild, { bar: true, name: name, source: text }); // 全宽沉浸,eye/复制看原文
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -700,21 +802,31 @@ window.matchMedia('(min-width: 960px)').addEventListener('change', () => { if (!
|
|||||||
const h = document.createElement('div');
|
const h = document.createElement('div');
|
||||||
h.className = 'pv-resizer';
|
h.className = 'pv-resizer';
|
||||||
pane.appendChild(h);
|
pane.appendChild(h);
|
||||||
let st = null;
|
let st = null; // { x: 起始 clientX, w: 起始宽度, lastX: 最新 clientX }
|
||||||
|
let rafId = 0;
|
||||||
|
// 改 --pv-w 会带着 #app 的 width/margin 一起重排(会话里的文字跟着重新折行),
|
||||||
|
// 一帧可能来十几个 pointermove,所以只在 rAF 里落一次值。
|
||||||
|
function commit() {
|
||||||
|
if (!st) return;
|
||||||
|
document.documentElement.style.setProperty('--pv-w', clamp(st.w + (st.lastX - st.x)) + 'px');
|
||||||
|
}
|
||||||
h.addEventListener('pointerdown', (e) => {
|
h.addEventListener('pointerdown', (e) => {
|
||||||
st = { x: e.clientX, w: pane.offsetWidth || clamp(window.innerWidth * 0.5) };
|
e.preventDefault(); // 从按下这一刻就掐掉拖选,否则会顺手选中一大片消息文字
|
||||||
|
st = { x: e.clientX, w: pane.offsetWidth || clamp(window.innerWidth * 0.5), lastX: e.clientX };
|
||||||
try { h.setPointerCapture(e.pointerId); } catch (_) {}
|
try { h.setPointerCapture(e.pointerId); } catch (_) {}
|
||||||
document.body.classList.add('pv-resizing');
|
document.body.classList.add('pv-resizing');
|
||||||
});
|
});
|
||||||
h.addEventListener('pointermove', (e) => {
|
h.addEventListener('pointermove', (e) => {
|
||||||
if (!st) return;
|
if (!st) return;
|
||||||
document.documentElement.style.setProperty('--pv-w', clamp(st.w + (e.clientX - st.x)) + 'px');
|
st.lastX = e.clientX;
|
||||||
|
if (!rafId) rafId = requestAnimationFrame(() => { rafId = 0; commit(); });
|
||||||
});
|
});
|
||||||
function end() {
|
function end() {
|
||||||
if (!st) return;
|
if (!st) return;
|
||||||
|
if (rafId) { cancelAnimationFrame(rafId); rafId = 0; commit(); } // 把最后一帧补上
|
||||||
|
const w = pane.offsetWidth;
|
||||||
st = null;
|
st = null;
|
||||||
document.body.classList.remove('pv-resizing');
|
document.body.classList.remove('pv-resizing');
|
||||||
const w = pane.offsetWidth;
|
|
||||||
if (w) localStorage.setItem('pv-w', String(w));
|
if (w) localStorage.setItem('pv-w', String(w));
|
||||||
}
|
}
|
||||||
h.addEventListener('pointerup', end);
|
h.addEventListener('pointerup', end);
|
||||||
@@ -728,7 +840,7 @@ window.matchMedia('(min-width: 960px)').addEventListener('change', () => { if (!
|
|||||||
// —— 通用 UI 卡片(stream.js 转发 SSE ui_card;任何 MCP 服务/工具回包附 type:"ui_card" 块即可产出)——
|
// —— 通用 UI 卡片(stream.js 转发 SSE ui_card;任何 MCP 服务/工具回包附 type:"ui_card" 块即可产出)——
|
||||||
// 产生方契约 {action, arg, title?, note?};新交互在动作注册表加一条即可,未知 action 忽略(向前兼容)。
|
// 产生方契约 {action, arg, title?, note?};新交互在动作注册表加一条即可,未知 action 忽略(向前兼容)。
|
||||||
// 图标由前端统一持有(与 pv-none 同一枚文档 SVG),产生方不提供图形,只给数据。
|
// 图标由前端统一持有(与 pv-none 同一枚文档 SVG),产生方不提供图形,只给数据。
|
||||||
const UI_CARD_ICON_DOC = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><polyline points="14 2 14 8 20 8"></polyline></svg>';
|
const UI_CARD_ICON_DOC = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"><use href="#i-file-doc"/></svg>';
|
||||||
const UI_CARD_ACTIONS = {
|
const UI_CARD_ACTIONS = {
|
||||||
// arg = 相对会话目录的文件路径,点击 = openFilePreview(office 走预览网关,其余类型走文本/图片渲染)
|
// arg = 相对会话目录的文件路径,点击 = openFilePreview(office 走预览网关,其余类型走文本/图片渲染)
|
||||||
open_preview: { go: '预览 ›', hint: '点击打开预览', icon: UI_CARD_ICON_DOC, run: (d) => openFilePreview(d.arg) },
|
open_preview: { go: '预览 ›', hint: '点击打开预览', icon: UI_CARD_ICON_DOC, run: (d) => openFilePreview(d.arg) },
|
||||||
|
|||||||
@@ -32,10 +32,10 @@
|
|||||||
'<span class="conv-title">' + esc(s.title || s.id) + '</span>' + drawerStatusDot(s) +
|
'<span class="conv-title">' + esc(s.title || s.id) + '</span>' + drawerStatusDot(s) +
|
||||||
'</button>' +
|
'</button>' +
|
||||||
'<button class="conv-pop" data-pop="' + esc(s.id) + '" title="在新窗口打开" aria-label="在新窗口打开">' +
|
'<button class="conv-pop" data-pop="' + esc(s.id) + '" title="在新窗口打开" aria-label="在新窗口打开">' +
|
||||||
'<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>' +
|
'<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><use href="#i-external"/></svg>' +
|
||||||
'</button>' +
|
'</button>' +
|
||||||
'<button class="conv-del" data-del="' + esc(s.id) + '" title="删除会话" aria-label="删除会话">' +
|
'<button class="conv-del" data-del="' + esc(s.id) + '" title="删除会话" aria-label="删除会话">' +
|
||||||
'<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h18"/><path d="M8 6V4a1 1 0 0 1 1-1h6a1 1 0 0 1 1 1v2"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M10 11v6"/><path d="M14 11v6"/></svg>' +
|
'<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><use href="#i-trash"/></svg>' +
|
||||||
'</button>' +
|
'</button>' +
|
||||||
'</div>';
|
'</div>';
|
||||||
}
|
}
|
||||||
@@ -201,12 +201,20 @@
|
|||||||
try { history.replaceState(null, '', url); } catch (_) {}
|
try { history.replaceState(null, '', url); } catch (_) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 收起预览:桌面分栏(#pv-pane,含 Git 面板)与窄屏全屏浮层都要收。
|
||||||
|
// pvCloseDoc 内部会 vcsSetMode(false),Git 面板跟着一起落下。
|
||||||
|
function closePreviewAll() {
|
||||||
|
if (typeof pvCloseDoc === 'function') pvCloseDoc();
|
||||||
|
const fs = document.getElementById('fs-viewer');
|
||||||
|
if (fs && !fs.classList.contains('hidden') && typeof closeFullscreen === 'function') closeFullscreen();
|
||||||
|
}
|
||||||
|
|
||||||
async function openSession(id) {
|
async function openSession(id) {
|
||||||
closeStream();
|
closeStream();
|
||||||
removeTyping();
|
removeTyping();
|
||||||
setFilesPanel(false); // 会话切换,收起文件面板防旧列表残留
|
setFilesPanel(false); // 会话切换,收起文件面板防旧列表残留
|
||||||
// 预览分栏故意不关:它现在是「随手看参考」的第三列,切会话时关掉会让用户反复重开。
|
// 切会话也要收起预览与 Git:里面是上一个会话的文件/仓库,留在旁边容易被当成新会话的
|
||||||
// 保留已渲染的内容(静态文件,不存在跨会话越权),点新会话的文件会自然覆盖。
|
closePreviewAll();
|
||||||
state.sessionId = id;
|
state.sessionId = id;
|
||||||
state.status = '';
|
state.status = '';
|
||||||
state.modelId = '';
|
state.modelId = '';
|
||||||
@@ -234,6 +242,9 @@
|
|||||||
renderAttachChips();
|
renderAttachChips();
|
||||||
clearUploadCards(); // 切会话清掉旧会话的上传卡片
|
clearUploadCards(); // 切会话清掉旧会话的上传卡片
|
||||||
renderDrawerList(); // 会话切换后立刻重画抽屉高亮,避免下次打开才看到更新
|
renderDrawerList(); // 会话切换后立刻重画抽屉高亮,避免下次打开才看到更新
|
||||||
|
// 文件树同理,而且更早:它的缓存按路径存、不含会话,晚一步清就会在抽屉里
|
||||||
|
// 先看到上个会话的文件。紧跟 sessionId 变更就清,不等 detail 回来。
|
||||||
|
if (window.refreshFileTree) window.refreshFileTree();
|
||||||
setView('chat');
|
setView('chat');
|
||||||
$('chat-view').innerHTML = '<div class="drawer-empty">加载中…</div>';
|
$('chat-view').innerHTML = '<div class="drawer-empty">加载中…</div>';
|
||||||
try {
|
try {
|
||||||
@@ -244,7 +255,6 @@
|
|||||||
state.deepThink = !!(detail.session && detail.session.deep_think);
|
state.deepThink = !!(detail.session && detail.session.deep_think);
|
||||||
$('deep-think-btn').classList.toggle('on', state.deepThink);
|
$('deep-think-btn').classList.toggle('on', state.deepThink);
|
||||||
connectStream();
|
connectStream();
|
||||||
if (window.refreshFileTree) window.refreshFileTree();
|
|
||||||
syncUrl(); // 详情拿到才写地址栏:坏链接不会把刷新后的页面也钉死在坏会话上
|
syncUrl(); // 详情拿到才写地址栏:坏链接不会把刷新后的页面也钉死在坏会话上
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (state.sessionId === id) {
|
if (state.sessionId === id) {
|
||||||
@@ -322,6 +332,7 @@
|
|||||||
closeStream();
|
closeStream();
|
||||||
removeTyping();
|
removeTyping();
|
||||||
setFilesPanel(false); // 新建会话,文件面板随之收起
|
setFilesPanel(false); // 新建会话,文件面板随之收起
|
||||||
|
closePreviewAll(); // 预览/Git 都属于上一个会话,新建时一并收起
|
||||||
state.sessionId = null;
|
state.sessionId = null;
|
||||||
state.sessionTitle = '';
|
state.sessionTitle = '';
|
||||||
state.sessionType = 'secretary';
|
state.sessionType = 'secretary';
|
||||||
@@ -346,6 +357,7 @@
|
|||||||
userPaused = false;
|
userPaused = false;
|
||||||
renderAttachChips();
|
renderAttachChips();
|
||||||
clearUploadCards();
|
clearUploadCards();
|
||||||
|
renderDrawerList(); // sessionId 已置空,重画抽屉把旧会话的选中态清掉
|
||||||
syncUrl();
|
syncUrl();
|
||||||
setView('welcome');
|
setView('welcome');
|
||||||
$('chat-view').innerHTML = '';
|
$('chat-view').innerHTML = '';
|
||||||
@@ -481,8 +493,37 @@
|
|||||||
if (act === 'model') openModelSwitch();
|
if (act === 'model') openModelSwitch();
|
||||||
else if (act === 'schedule') openScheduleModal();
|
else if (act === 'schedule') openScheduleModal();
|
||||||
else if (act === 'compact') summarizeChat();
|
else if (act === 'compact') summarizeChat();
|
||||||
|
else if (act === 'theme') cycleTheme();
|
||||||
else if (act === 'new') newChat();
|
else if (act === 'new') newChat();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---------- 主题(浅/深两态,默认浅色;色板全在 style.css 变量里)----------
|
||||||
|
function themeMode() { return document.documentElement.getAttribute('data-theme-mode') === 'dark' ? 'dark' : 'light'; }
|
||||||
|
function applyTheme(mode) {
|
||||||
|
const m = mode === 'dark' ? 'dark' : 'light';
|
||||||
|
document.documentElement.setAttribute('data-theme', m);
|
||||||
|
document.documentElement.setAttribute('data-theme-mode', m);
|
||||||
|
try { localStorage.setItem('agent-theme', m); } catch (_) {}
|
||||||
|
const meta = document.querySelector('meta[name="theme-color"]');
|
||||||
|
if (meta) meta.setAttribute('content', m === 'dark' ? '#0d1117' : '#3964FE');
|
||||||
|
syncThemeBtns();
|
||||||
|
}
|
||||||
|
function cycleTheme() { applyTheme(themeMode() === 'dark' ? 'light' : 'dark'); }
|
||||||
|
function syncThemeBtns() {
|
||||||
|
const dark = themeMode() === 'dark';
|
||||||
|
const lbl = dark ? '主题:深色' : '主题:浅色';
|
||||||
|
['theme-toggle', 'theme-toggle-mobile'].forEach(function (id) {
|
||||||
|
const b = $(id);
|
||||||
|
if (!b) return;
|
||||||
|
b.querySelectorAll('svg').forEach(function (s, k) { s.classList.toggle('hidden', k !== (dark ? 1 : 0)); });
|
||||||
|
});
|
||||||
|
const t = $('theme-toggle');
|
||||||
|
if (t) { t.title = lbl; t.dataset.tip = lbl; }
|
||||||
|
const lab = $('theme-label-mobile');
|
||||||
|
if (lab) lab.textContent = dark ? '深色' : '浅色'; // 副标题只写当前值,主文案是动作
|
||||||
|
}
|
||||||
|
window.applyTheme = applyTheme;
|
||||||
|
window.cycleTheme = cycleTheme;
|
||||||
// 桌面属性区(模型/定时任务/压缩)与移动菜单项共用同一批 data-act,事件只在这里绑一次。
|
// 桌面属性区(模型/定时任务/压缩)与移动菜单项共用同一批 data-act,事件只在这里绑一次。
|
||||||
(function bindHeaderActions() {
|
(function bindHeaderActions() {
|
||||||
document.querySelectorAll('#header-meta [data-act], #header-actions [data-act]').forEach(el => {
|
document.querySelectorAll('#header-meta [data-act], #header-actions [data-act]').forEach(el => {
|
||||||
@@ -495,6 +536,7 @@
|
|||||||
if (!e.target.closest('#header-actions')) closeHeaderMenu();
|
if (!e.target.closest('#header-actions')) closeHeaderMenu();
|
||||||
});
|
});
|
||||||
document.addEventListener('keydown', e => { if (e.key === 'Escape') closeHeaderMenu(); });
|
document.addEventListener('keydown', e => { if (e.key === 'Escape') closeHeaderMenu(); });
|
||||||
|
syncThemeBtns(); // 按钮图标/文字跟着当前主题落一次
|
||||||
})();
|
})();
|
||||||
|
|
||||||
// ---------- 定时任务(弹窗改频次/提示词;无任务时同一弹窗即新建) ----------
|
// ---------- 定时任务(弹窗改频次/提示词;无任务时同一弹窗即新建) ----------
|
||||||
@@ -814,7 +856,7 @@
|
|||||||
wrap.innerHTML =
|
wrap.innerHTML =
|
||||||
'<div class="modal">' +
|
'<div class="modal">' +
|
||||||
'<button class="modal-close-btn" data-act="cancel" aria-label="关闭">' +
|
'<button class="modal-close-btn" data-act="cancel" aria-label="关闭">' +
|
||||||
'<svg viewBox="0 0 24 24"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>' +
|
'<svg viewBox="0 0 24 24"><use href="#i-x-line-b"/></svg>' +
|
||||||
'</button>' +
|
'</button>' +
|
||||||
'<h3 id="compress-modal-title">压缩上下文</h3>' +
|
'<h3 id="compress-modal-title">压缩上下文</h3>' +
|
||||||
'<div class="modal-body" style="font-size:14px;line-height:1.55;color:#555;padding:4px 0 12px;">' +
|
'<div class="modal-body" style="font-size:14px;line-height:1.55;color:#555;padding:4px 0 12px;">' +
|
||||||
|
|||||||
@@ -146,7 +146,7 @@
|
|||||||
// 快照里的 id 全部剥除,防止重复 id 干扰 $('…') 查找;仅作动画背景,滑完由 renderSetPage 重渲染真页。
|
// 快照里的 id 全部剥除,防止重复 id 干扰 $('…') 查找;仅作动画背景,滑完由 renderSetPage 重渲染真页。
|
||||||
function snapSetPage() {
|
function snapSetPage() {
|
||||||
const box = document.createElement('div');
|
const box = document.createElement('div');
|
||||||
box.innerHTML = '<header class="header"><button class="icon-btn" tabindex="-1"><svg class="ic" viewBox="0 0 24 24"><polyline points="15 18 9 12 15 6"></polyline></svg></button>' +
|
box.innerHTML = '<header class="header"><button class="icon-btn" tabindex="-1"><svg class="ic" viewBox="0 0 24 24"><use href="#i-chevron-left"/></svg></button>' +
|
||||||
'<div class="header-center"><div class="header-title">' + esc($('set-title').textContent) + '</div></div>' +
|
'<div class="header-center"><div class="header-title">' + esc($('set-title').textContent) + '</div></div>' +
|
||||||
'<div class="header-right">' + $('set-actions').innerHTML + '</div></header>' +
|
'<div class="header-right">' + $('set-actions').innerHTML + '</div></header>' +
|
||||||
'<div class="set-under-body">' + $('set-body').innerHTML + '</div>';
|
'<div class="set-under-body">' + $('set-body').innerHTML + '</div>';
|
||||||
@@ -281,17 +281,17 @@
|
|||||||
// ---------- 页:设置主页(卡片入口) ----------
|
// ---------- 页:设置主页(卡片入口) ----------
|
||||||
const SET_CARDS = [
|
const SET_CARDS = [
|
||||||
{ go: 'account', name: '账户', desc: '修改密码 · 用户画像 · 退出登录',
|
{ go: 'account', name: '账户', desc: '修改密码 · 用户画像 · 退出登录',
|
||||||
icon: '<svg class="ic" viewBox="0 0 24 24"><circle cx="12" cy="8" r="4"></circle><path d="M4 21c0-4 4-6 8-6s8 2 8 6"></path></svg>' },
|
icon: '<svg class="ic" viewBox="0 0 24 24"><use href="#i-user"/></svg>' },
|
||||||
{ go: 'users', name: '用户', desc: '账号 · 角色 · 默认模型', adminOnly: true, needAuth: true,
|
{ go: 'users', name: '用户', desc: '账号 · 角色 · 默认模型', adminOnly: true, needAuth: true,
|
||||||
icon: '<svg class="ic" viewBox="0 0 24 24"><circle cx="9" cy="8" r="3.5"></circle><path d="M2 21c0-3.6 3.1-5.5 7-5.5s7 1.9 7 5.5"></path><path d="M16 8.5a3 3 0 0 1 0 6"></path><path d="M18 21c0-2.8-1.4-4.5-4-5.2"></path></svg>' },
|
icon: '<svg class="ic" viewBox="0 0 24 24"><use href="#i-users"/></svg>' },
|
||||||
{ go: 'service', name: '服务', desc: '服务状态 · 系统配置', adminOnly: true,
|
{ go: 'service', name: '服务', desc: '服务状态 · 系统配置', adminOnly: true,
|
||||||
icon: '<svg class="ic" viewBox="0 0 24 24"><line x1="4" y1="21" x2="4" y2="14"></line><line x1="4" y1="10" x2="4" y2="3"></line><line x1="12" y1="21" x2="12" y2="12"></line><line x1="12" y1="8" x2="12" y2="3"></line><line x1="20" y1="21" x2="20" y2="16"></line><line x1="20" y1="12" x2="20" y2="3"></line><line x1="1" y1="14" x2="7" y2="14"></line><line x1="9" y1="8" x2="15" y2="8"></line><line x1="17" y1="16" x2="23" y2="16"></line></svg>' },
|
icon: '<svg class="ic" viewBox="0 0 24 24"><use href="#i-sliders-v"/></svg>' },
|
||||||
{ go: 'skills', name: '技能', desc: '技能管理 · 技能文件编辑', adminOnly: true,
|
{ go: 'skills', name: '技能', desc: '技能管理 · 技能文件编辑', adminOnly: true,
|
||||||
icon: '<svg class="ic" viewBox="0 0 24 24"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"></polygon></svg>' },
|
icon: '<svg class="ic" viewBox="0 0 24 24"><use href="#i-zap"/></svg>' },
|
||||||
{ go: 'models', name: '模型', desc: '模型池状态 · 增删改', adminOnly: true,
|
{ go: 'models', name: '模型', desc: '模型池状态 · 增删改', adminOnly: true,
|
||||||
icon: '<svg class="ic" viewBox="0 0 24 24"><rect x="4" y="4" width="16" height="16" rx="2"></rect><rect x="9" y="9" width="6" height="6"></rect><line x1="9" y1="1" x2="9" y2="4"></line><line x1="15" y1="1" x2="15" y2="4"></line><line x1="9" y1="20" x2="9" y2="23"></line><line x1="15" y1="20" x2="15" y2="23"></line><line x1="20" y1="9" x2="23" y2="9"></line><line x1="20" y1="14" x2="23" y2="14"></line><line x1="1" y1="9" x2="4" y2="9"></line><line x1="1" y1="14" x2="4" y2="14"></line></svg>' },
|
icon: '<svg class="ic" viewBox="0 0 24 24"><use href="#i-cpu"/></svg>' },
|
||||||
{ go: 'mcp', name: 'MCP', desc: 'MCP 服务 · 增删改', adminOnly: true,
|
{ go: 'mcp', name: 'MCP', desc: 'MCP 服务 · 增删改', adminOnly: true,
|
||||||
icon: '<svg class="ic" viewBox="0 0 24 24"><rect x="3" y="4" width="18" height="16" rx="2"></rect><line x1="3" y1="10" x2="21" y2="10"></line><circle cx="7" cy="15" r="1.2" fill="currentColor" stroke="none"></circle><circle cx="12" cy="15" r="1.2" fill="currentColor" stroke="none"></circle><circle cx="17" cy="15" r="1.2" fill="currentColor" stroke="none"></circle></svg>' },
|
icon: '<svg class="ic" viewBox="0 0 24 24"><use href="#i-layout"/></svg>' },
|
||||||
];
|
];
|
||||||
function setPageHome(ctx) {
|
function setPageHome(ctx) {
|
||||||
setTitle('设置');
|
setTitle('设置');
|
||||||
@@ -303,7 +303,7 @@
|
|||||||
'<span class="set-ico">' + c.icon + '</span>' +
|
'<span class="set-ico">' + c.icon + '</span>' +
|
||||||
'<span class="set-tt"><span class="set-name">' + c.name + '</span>' +
|
'<span class="set-tt"><span class="set-name">' + c.name + '</span>' +
|
||||||
'<span class="set-desc">' + c.desc + '</span></span>' +
|
'<span class="set-desc">' + c.desc + '</span></span>' +
|
||||||
'<svg class="ic sm set-arrow" viewBox="0 0 24 24"><polyline points="9 6 15 12 9 18"></polyline></svg>' +
|
'<svg class="ic sm set-arrow" viewBox="0 0 24 24"><use href="#i-chevron-right-b"/></svg>' +
|
||||||
'</button>').join('') + '</div>');
|
'</button>').join('') + '</div>');
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -395,7 +395,7 @@
|
|||||||
async function setPageUsers(ctx) {
|
async function setPageUsers(ctx) {
|
||||||
setTitle('用户');
|
setTitle('用户');
|
||||||
setActions('<button class="icon-btn" title="添加用户" onclick="sUI.openUserAdd()">' +
|
setActions('<button class="icon-btn" title="添加用户" onclick="sUI.openUserAdd()">' +
|
||||||
'<svg class="ic" viewBox="0 0 24 24"><line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line></svg></button>');
|
'<svg class="ic" viewBox="0 0 24 24"><use href="#i-plus"/></svg></button>');
|
||||||
setBody('<div class="set-scroll" id="user-list"><div class="empty-tip">加载中…</div></div>');
|
setBody('<div class="set-scroll" id="user-list"><div class="empty-tip">加载中…</div></div>');
|
||||||
try {
|
try {
|
||||||
const r = await req('GET', '/api/users');
|
const r = await req('GET', '/api/users');
|
||||||
@@ -689,7 +689,7 @@
|
|||||||
async function setPageService(ctx) {
|
async function setPageService(ctx) {
|
||||||
setTitle('服务');
|
setTitle('服务');
|
||||||
setActions('<button class="icon-btn" title="编辑配置文件" onclick="sUI.openCfg()">' +
|
setActions('<button class="icon-btn" title="编辑配置文件" onclick="sUI.openCfg()">' +
|
||||||
'<svg class="ic" viewBox="0 0 24 24"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path><path d="M18.5 2.5a2.12 2.12 0 0 1 3 3L12 15l-4 1 1-4z"></path></svg></button>');
|
'<svg class="ic" viewBox="0 0 24 24"><use href="#i-edit"/></svg></button>');
|
||||||
setBody('<div class="set-scroll" id="svc-body"><div class="empty-tip">加载中…</div></div>');
|
setBody('<div class="set-scroll" id="svc-body"><div class="empty-tip">加载中…</div></div>');
|
||||||
try {
|
try {
|
||||||
const [st, cg] = await Promise.all([
|
const [st, cg] = await Promise.all([
|
||||||
@@ -769,7 +769,7 @@
|
|||||||
async function setPageCfgEditor(ctx) {
|
async function setPageCfgEditor(ctx) {
|
||||||
setTitle('config.yml 原文');
|
setTitle('config.yml 原文');
|
||||||
setActions('<button class="icon-btn" title="校验并保存" onclick="sUI.saveCfg()">' +
|
setActions('<button class="icon-btn" title="校验并保存" onclick="sUI.saveCfg()">' +
|
||||||
'<svg class="ic" viewBox="0 0 24 24"><polyline points="20 6 9 17 4 12"></polyline></svg></button>');
|
'<svg class="ic" viewBox="0 0 24 24"><use href="#i-check"/></svg></button>');
|
||||||
setBody('<div class="set-editor"><div class="cfg-err hidden" id="cfg-editor-err"></div>' +
|
setBody('<div class="set-editor"><div class="cfg-err hidden" id="cfg-editor-err"></div>' +
|
||||||
'<textarea id="set-editor-area" spellcheck="false" autocomplete="off" autocapitalize="off"></textarea></div>');
|
'<textarea id="set-editor-area" spellcheck="false" autocomplete="off" autocapitalize="off"></textarea></div>');
|
||||||
try {
|
try {
|
||||||
@@ -812,7 +812,7 @@
|
|||||||
SET.curSkill = null;
|
SET.curSkill = null;
|
||||||
setTitle('技能管理');
|
setTitle('技能管理');
|
||||||
setActions('<button class="icon-btn" title="新建技能" onclick="sUI.openCreate()">' +
|
setActions('<button class="icon-btn" title="新建技能" onclick="sUI.openCreate()">' +
|
||||||
'<svg class="ic" viewBox="0 0 24 24"><line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line></svg></button>');
|
'<svg class="ic" viewBox="0 0 24 24"><use href="#i-plus"/></svg></button>');
|
||||||
setBody('<div class="set-scroll" id="skills-list"><div class="empty-tip">加载中…</div></div>');
|
setBody('<div class="set-scroll" id="skills-list"><div class="empty-tip">加载中…</div></div>');
|
||||||
try {
|
try {
|
||||||
const rows = await req('GET', '/api/skills');
|
const rows = await req('GET', '/api/skills');
|
||||||
@@ -855,7 +855,7 @@
|
|||||||
setTitle(SET.curSkill);
|
setTitle(SET.curSkill);
|
||||||
setActions('<label class="icon-btn" title="上传文件">' +
|
setActions('<label class="icon-btn" title="上传文件">' +
|
||||||
'<input type="file" style="display:none;" onchange="sUI.onUpload(event)">' +
|
'<input type="file" style="display:none;" onchange="sUI.onUpload(event)">' +
|
||||||
'<svg class="ic" viewBox="0 0 24 24"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="17 8 12 3 7 8"></polyline><line x1="12" y1="3" x2="12" y2="15"></line></svg></label>');
|
'<svg class="ic" viewBox="0 0 24 24"><use href="#i-upload-cloud"/></svg></label>');
|
||||||
setBody('<div class="set-scroll" id="skill-detail"><div class="empty-tip">加载中…</div></div>');
|
setBody('<div class="set-scroll" id="skill-detail"><div class="empty-tip">加载中…</div></div>');
|
||||||
try {
|
try {
|
||||||
const d = await req('GET', '/api/skills/' + encodeURIComponent(SET.curSkill));
|
const d = await req('GET', '/api/skills/' + encodeURIComponent(SET.curSkill));
|
||||||
@@ -871,7 +871,7 @@
|
|||||||
el.innerHTML = '<div class="skill-files">' + d.files.map(f => {
|
el.innerHTML = '<div class="skill-files">' + d.files.map(f => {
|
||||||
const a = encodeURIComponent(f.filename);
|
const a = encodeURIComponent(f.filename);
|
||||||
return '<div class="file-row" onclick="sUI.editFile(\'' + a + '\')">' +
|
return '<div class="file-row" onclick="sUI.editFile(\'' + a + '\')">' +
|
||||||
'<svg class="file-ico" viewBox="0 0 24 24"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><polyline points="14 2 14 8 20 8"></polyline></svg>' +
|
'<svg class="file-ico" viewBox="0 0 24 24"><use href="#i-file-doc"/></svg>' +
|
||||||
'<span class="file-name">' + esc(f.filename) + '</span>' +
|
'<span class="file-name">' + esc(f.filename) + '</span>' +
|
||||||
'<span class="file-size">' + fmtSize(f.size) + '</span>' +
|
'<span class="file-size">' + fmtSize(f.size) + '</span>' +
|
||||||
'<button class="file-act" onclick="event.stopPropagation();sUI.editFile(\'' + a + '\')">编辑</button>' +
|
'<button class="file-act" onclick="event.stopPropagation();sUI.editFile(\'' + a + '\')">编辑</button>' +
|
||||||
@@ -885,7 +885,7 @@
|
|||||||
function setPageSkillEditor(ctx) {
|
function setPageSkillEditor(ctx) {
|
||||||
setTitle(SET.editorLabel || '编辑文件');
|
setTitle(SET.editorLabel || '编辑文件');
|
||||||
setActions('<button class="icon-btn" title="保存" onclick="sUI.saveFile()">' +
|
setActions('<button class="icon-btn" title="保存" onclick="sUI.saveFile()">' +
|
||||||
'<svg class="ic" viewBox="0 0 24 24"><polyline points="20 6 9 17 4 12"></polyline></svg></button>');
|
'<svg class="ic" viewBox="0 0 24 24"><use href="#i-check"/></svg></button>');
|
||||||
setBody('<div class="set-editor"><textarea id="set-editor-area" spellcheck="false" autocomplete="off" autocapitalize="off"></textarea></div>');
|
setBody('<div class="set-editor"><textarea id="set-editor-area" spellcheck="false" autocomplete="off" autocapitalize="off"></textarea></div>');
|
||||||
$('set-editor-area').value = SET.editorText;
|
$('set-editor-area').value = SET.editorText;
|
||||||
}
|
}
|
||||||
@@ -1066,7 +1066,7 @@
|
|||||||
if (ev) ev.stopPropagation(); // 冒泡到分组头会误触折叠/展开
|
if (ev) ev.stopPropagation(); // 冒泡到分组头会误触折叠/展开
|
||||||
fetchBalance(pi + '-' + ki, pi, ki, true);
|
fetchBalance(pi + '-' + ki, pi, ki, true);
|
||||||
}
|
}
|
||||||
const BAL_REFRESH_SVG = '<svg viewBox="0 0 24 24"><polyline points="23 4 23 10 17 10"></polyline><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"></path></svg>';
|
const BAL_REFRESH_SVG = '<svg viewBox="0 0 24 24"><use href="#i-refresh"/></svg>';
|
||||||
// 平台卡折叠/展开(gk = 'p'+pi)。首次展开:给该平台每个 Key 行自动查一次余额(每页会话一次;手动刷新不受限)。
|
// 平台卡折叠/展开(gk = 'p'+pi)。首次展开:给该平台每个 Key 行自动查一次余额(每页会话一次;手动刷新不受限)。
|
||||||
function toggleModelGroup(gk) {
|
function toggleModelGroup(gk) {
|
||||||
const on = !SET.expandedGroups[gk];
|
const on = !SET.expandedGroups[gk];
|
||||||
@@ -1159,7 +1159,7 @@
|
|||||||
}).join('') : '';
|
}).join('') : '';
|
||||||
return '<div class="model-group' + (open ? ' open' : '') + '" id="mgrp-' + gk + '">' +
|
return '<div class="model-group' + (open ? ' open' : '') + '" id="mgrp-' + gk + '">' +
|
||||||
'<div class="model-group-head" onclick="sUI.toggleGroup(\'' + gk + '\')">' +
|
'<div class="model-group-head" onclick="sUI.toggleGroup(\'' + gk + '\')">' +
|
||||||
'<svg class="model-group-caret" viewBox="0 0 24 24"><polyline points="9 6 15 12 9 18"></polyline></svg>' +
|
'<svg class="model-group-caret" viewBox="0 0 24 24"><use href="#i-chevron-right-b"/></svg>' +
|
||||||
'<span class="model-group-name">' + esc(p.name || ('平台' + pi)) + '</span>' +
|
'<span class="model-group-name">' + esc(p.name || ('平台' + pi)) + '</span>' +
|
||||||
'<span class="model-group-badge">' + keys.length + ' keys</span>' +
|
'<span class="model-group-badge">' + keys.length + ' keys</span>' +
|
||||||
'<span class="model-group-meta">' + models.filter(m => m.enable !== false).length + ' / ' + models.length + ' 模型</span>' +
|
'<span class="model-group-meta">' + models.filter(m => m.enable !== false).length + ' / ' + models.length + ' 模型</span>' +
|
||||||
@@ -1212,7 +1212,7 @@
|
|||||||
function setPageModels(ctx) {
|
function setPageModels(ctx) {
|
||||||
setTitle('模型池');
|
setTitle('模型池');
|
||||||
setActions('<button class="icon-btn" title="添加模型" onclick="sUI.openAdd()">' +
|
setActions('<button class="icon-btn" title="添加模型" onclick="sUI.openAdd()">' +
|
||||||
'<svg class="ic" viewBox="0 0 24 24"><line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line></svg></button>');
|
'<svg class="ic" viewBox="0 0 24 24"><use href="#i-plus"/></svg></button>');
|
||||||
setBody('<div class="set-scroll" id="model-cards"><div class="empty-tip">加载中…</div></div>');
|
setBody('<div class="set-scroll" id="model-cards"><div class="empty-tip">加载中…</div></div>');
|
||||||
// 余额与展开态跨设置内导航保持(仅 closeSettings 回会话页时重置),重进本页不重复查余额
|
// 余额与展开态跨设置内导航保持(仅 closeSettings 回会话页时重置),重进本页不重复查余额
|
||||||
loadModelCards(ctx);
|
loadModelCards(ctx);
|
||||||
@@ -1260,7 +1260,7 @@
|
|||||||
}
|
}
|
||||||
function pfNewModel() {
|
function pfNewModel() {
|
||||||
const r = { ref: null, id: '', vision: true, enable: true, display_name: '', profile: '',
|
const r = { ref: null, id: '', vision: true, enable: true, display_name: '', profile: '',
|
||||||
extra_params: '', thinking_params: '', reasoning_ack_field: '', max_context: 0, adv: false };
|
extra_params: '', thinking_params: '', reasoning_ack_field: '', max_context: 0, store: false, adv: false };
|
||||||
if (pfEdit) applyModelDefaults(r, pfEdit.preset);
|
if (pfEdit) applyModelDefaults(r, pfEdit.preset);
|
||||||
return r;
|
return r;
|
||||||
}
|
}
|
||||||
@@ -1284,6 +1284,7 @@
|
|||||||
thinking_params: pfJsonText(m.thinking_params),
|
thinking_params: pfJsonText(m.thinking_params),
|
||||||
reasoning_ack_field: m.reasoning_ack_field || '',
|
reasoning_ack_field: m.reasoning_ack_field || '',
|
||||||
max_context: Number(m.max_context) || 0,
|
max_context: Number(m.max_context) || 0,
|
||||||
|
store: m.store === true,
|
||||||
adv: false,
|
adv: false,
|
||||||
})),
|
})),
|
||||||
};
|
};
|
||||||
@@ -1374,6 +1375,7 @@
|
|||||||
'<div class="mpe-cks">' +
|
'<div class="mpe-cks">' +
|
||||||
'<label class="mpe-ck"><input type="checkbox"' + (r.vision ? ' checked' : '') + ' onchange="sUI.mModVision(' + i + ',this.checked)">图片输入</label>' +
|
'<label class="mpe-ck"><input type="checkbox"' + (r.vision ? ' checked' : '') + ' onchange="sUI.mModVision(' + i + ',this.checked)">图片输入</label>' +
|
||||||
'<label class="mpe-ck"><input type="checkbox"' + (r.enable !== false ? ' checked' : '') + ' onchange="sUI.mModEnable(' + i + ',this.checked)">启用</label>' +
|
'<label class="mpe-ck"><input type="checkbox"' + (r.enable !== false ? ' checked' : '') + ' onchange="sUI.mModEnable(' + i + ',this.checked)">启用</label>' +
|
||||||
|
'<label class="mpe-ck" title="只发新增消息,需上游有 context relay"><input type="checkbox"' + (r.store ? ' checked' : '') + ' onchange="sUI.mModField(' + i + ',\'store\',this.checked)">增量上下文</label>' +
|
||||||
'<button type="button" class="mpe-adv-btn" onclick="sUI.mAdvToggle(' + i + ')">' + (r.adv ? '收起' : '高级') + '</button>' +
|
'<button type="button" class="mpe-adv-btn" onclick="sUI.mAdvToggle(' + i + ')">' + (r.adv ? '收起' : '高级') + '</button>' +
|
||||||
'</div>' + adv +
|
'</div>' + adv +
|
||||||
'</div>';
|
'</div>';
|
||||||
@@ -1430,6 +1432,7 @@
|
|||||||
if (ra) nv.reasoning_ack_field = ra;
|
if (ra) nv.reasoning_ack_field = ra;
|
||||||
const mc = Math.max(0, parseInt(r.max_context, 10) || 0);
|
const mc = Math.max(0, parseInt(r.max_context, 10) || 0);
|
||||||
if (mc) nv.max_context = mc;
|
if (mc) nv.max_context = mc;
|
||||||
|
if (r.store === true) nv.store = true; // 缺省 false,只在勾选时写
|
||||||
return nv;
|
return nv;
|
||||||
}
|
}
|
||||||
// 根据工作态算批量编辑:原地改(值变更项) → 删行(降序) → 新增行(append)。
|
// 根据工作态算批量编辑:原地改(值变更项) → 删行(降序) → 新增行(append)。
|
||||||
@@ -1512,6 +1515,12 @@
|
|||||||
if (mc !== curMc) {
|
if (mc !== curMc) {
|
||||||
edits.push(mc ? { path: mp.concat('max_context'), value: mc } : { path: mp.concat('max_context'), op: 'delete' });
|
edits.push(mc ? { path: mp.concat('max_context'), value: mc } : { path: mp.concat('max_context'), op: 'delete' });
|
||||||
}
|
}
|
||||||
|
// 增量上下文:缺省不写,只在勾选时落键,取消勾选则删键
|
||||||
|
const curSt = om.store === true;
|
||||||
|
const st = r.store === true;
|
||||||
|
if (st !== curSt) {
|
||||||
|
edits.push(st ? { path: mp.concat('store'), value: true } : { path: mp.concat('store'), op: 'delete' });
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
edits.push({ op: 'append', path: ['platforms', pfEdit.idx, 'models'], value: pfModelValue(r) });
|
edits.push({ op: 'append', path: ['platforms', pfEdit.idx, 'models'], value: pfModelValue(r) });
|
||||||
}
|
}
|
||||||
@@ -1622,7 +1631,7 @@
|
|||||||
async function setPageMcp(ctx) {
|
async function setPageMcp(ctx) {
|
||||||
setTitle('MCP 服务');
|
setTitle('MCP 服务');
|
||||||
setActions('<button class="icon-btn" title="添加 MCP 服务" onclick="mcpUI.add()">' +
|
setActions('<button class="icon-btn" title="添加 MCP 服务" onclick="mcpUI.add()">' +
|
||||||
'<svg class="ic" viewBox="0 0 24 24"><line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line></svg></button>');
|
'<svg class="ic" viewBox="0 0 24 24"><use href="#i-plus"/></svg></button>');
|
||||||
setBody('<div class="set-scroll" id="mcp-list"><div class="empty-tip">加载中…</div></div>');
|
setBody('<div class="set-scroll" id="mcp-list"><div class="empty-tip">加载中…</div></div>');
|
||||||
await loadMcpList(ctx);
|
await loadMcpList(ctx);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -99,8 +99,8 @@
|
|||||||
// 队列本身在服务端(engine.pendings),关页面/换设备/重连都不丢;这里只负责画。
|
// 队列本身在服务端(engine.pendings),关页面/换设备/重连都不丢;这里只负责画。
|
||||||
// 每条一行;只有队首有「干预 / 立即发送」,其余显示排队中(不能越过前一条先发)。
|
// 每条一行;只有队首有「干预 / 立即发送」,其余显示排队中(不能越过前一条先发)。
|
||||||
// 两条操作各配一枚图标:笔=撤回编辑(正文退回输入框),垃圾桶=直接丢弃这条
|
// 两条操作各配一枚图标:笔=撤回编辑(正文退回输入框),垃圾桶=直接丢弃这条
|
||||||
const SQ_EDIT_ICON = '<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20h9"/><path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg>';
|
const SQ_EDIT_ICON = '<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><use href="#i-pencil-b"/></svg>';
|
||||||
const SQ_TRASH_ICON = '<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h18"/><path d="M8 6V4a1 1 0 0 1 1-1h6a1 1 0 0 1 1 1v2"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M10 11v6"/><path d="M14 11v6"/></svg>';
|
const SQ_TRASH_ICON = '<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><use href="#i-trash"/></svg>';
|
||||||
|
|
||||||
function renderSendQueue() {
|
function renderSendQueue() {
|
||||||
const box = $('send-queue');
|
const box = $('send-queue');
|
||||||
@@ -313,6 +313,7 @@
|
|||||||
state.streamEl.className = 'bubble-ai' + (r.fmt ? ' md' : ''); // 增量期间是纯文本,收尾统一换 md 排版
|
state.streamEl.className = 'bubble-ai' + (r.fmt ? ' md' : ''); // 增量期间是纯文本,收尾统一换 md 排版
|
||||||
state.streamEl.innerHTML = r.html;
|
state.streamEl.innerHTML = r.html;
|
||||||
decorateCodePre(state.streamEl); // 流式期间不插按钮(每帧整块换 innerHTML),收尾统一装饰一次
|
decorateCodePre(state.streamEl); // 流式期间不插按钮(每帧整块换 innerHTML),收尾统一装饰一次
|
||||||
|
pvHighlightMdCode(state.streamEl); // 围栏代码块上色
|
||||||
} else {
|
} else {
|
||||||
// 无文本时去掉气泡(纯工具调用/纯思考也要保留思考面板)
|
// 无文本时去掉气泡(纯工具调用/纯思考也要保留思考面板)
|
||||||
state.streamEl.remove();
|
state.streamEl.remove();
|
||||||
@@ -326,6 +327,7 @@
|
|||||||
bubble.className = 'bubble-ai' + (r.fmt ? ' md' : '');
|
bubble.className = 'bubble-ai' + (r.fmt ? ' md' : '');
|
||||||
bubble.innerHTML = r.html;
|
bubble.innerHTML = r.html;
|
||||||
decorateCodePre(bubble);
|
decorateCodePre(bubble);
|
||||||
|
pvHighlightMdCode(bubble);
|
||||||
state.streamWrap.appendChild(bubble);
|
state.streamWrap.appendChild(bubble);
|
||||||
}
|
}
|
||||||
// 「压缩」总结回合的最终答复(后端已保证只有压缩回合里首条无工具调用的收尾回复才带 is_summary,
|
// 「压缩」总结回合的最终答复(后端已保证只有压缩回合里首条无工具调用的收尾回复才带 is_summary,
|
||||||
|
|||||||
+42
-10
@@ -54,16 +54,22 @@
|
|||||||
const parts = [];
|
const parts = [];
|
||||||
parts.push('<div class="vcs-list">');
|
parts.push('<div class="vcs-list">');
|
||||||
if (st.repo) {
|
if (st.repo) {
|
||||||
parts.push('<div class="vcs-repo">' + esc(st.repo.root) + (st.repo.branch ? ' · ' + esc(st.repo.branch) : '') + '</div>');
|
const rm = st.repo.remote;
|
||||||
|
parts.push('<div class="vcs-repo">' + esc(st.repo.root) + (st.repo.branch ? ' · ' + esc(st.repo.branch) : '') +
|
||||||
|
' · <span class="vcs-remote' + (rm ? '' : ' none') + '" title="' + esc(rm ? rm.url : '未配置 remote') + '">' +
|
||||||
|
esc(rm ? rm.name : '无 remote') + '</span></div>');
|
||||||
}
|
}
|
||||||
if (st.worktree && st.worktree.files) {
|
if (st.worktree && st.worktree.files) {
|
||||||
parts.push('<div class="vcs-item wt" data-act="worktree">' +
|
parts.push('<div class="vcs-item wt" data-act="worktree">' +
|
||||||
'<div class="t">未提交的改动</div>' +
|
'<div class="t">未提交的改动</div>' +
|
||||||
'<div class="m">' + st.worktree.files + ' 个文件有变动</div></div>');
|
'<div class="m">' + st.worktree.files + ' 个文件有变动</div></div>');
|
||||||
}
|
}
|
||||||
|
const up = st.repo && st.repo.upstream;
|
||||||
for (const c of st.commits) {
|
for (const c of st.commits) {
|
||||||
parts.push('<div class="vcs-item" data-act="commit" data-id="' + esc(c.id) + '">' +
|
const atUp = up && c.id === up.id;
|
||||||
'<div class="t">' + esc(c.subject) + '</div>' +
|
parts.push('<div class="vcs-item' + (atUp ? ' at-up' : '') + '" data-act="commit" data-id="' + esc(c.id) + '">' +
|
||||||
|
'<div class="t">' + esc(c.subject) +
|
||||||
|
(atUp ? ' <span class="vcs-up" title="远端 ' + esc(up.ref) + ' 指向这里">' + esc(up.ref) + '</span>' : '') + '</div>' +
|
||||||
'<div class="m">' + esc(c.author) + ' · ' + esc(fmtTime(c.time)) + ' · ' + esc(c.short) + '</div></div>');
|
'<div class="m">' + esc(c.author) + ' · ' + esc(fmtTime(c.time)) + ' · ' + esc(c.short) + '</div></div>');
|
||||||
}
|
}
|
||||||
if (!st.commits.length && !(st.worktree && st.worktree.files)) {
|
if (!st.commits.length && !(st.worktree && st.worktree.files)) {
|
||||||
@@ -75,9 +81,21 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ---------- 详情(提交 / 未提交共用)----------
|
// ---------- 详情(提交 / 未提交共用)----------
|
||||||
function lineHtml(cls, oldNo, newNo, text) {
|
// 语法高亮:与预览共用 PV_LANG(preview.js)。只能逐行高亮:diff 是片段,多行注释/三引号串
|
||||||
|
// 本来就拼不完整;逐行反而不会把行号与红绿底色搞乱。
|
||||||
|
function prismLang(path) {
|
||||||
|
if (typeof PV_LANG === 'undefined' || typeof Prism === 'undefined' || !Prism.languages) return null;
|
||||||
|
const m = /\.([^.\\/]+)$/.exec(String(path || ''));
|
||||||
|
const lang = m && PV_LANG[m[1].toLowerCase()];
|
||||||
|
return lang && Prism.languages[lang] ? lang : null;
|
||||||
|
}
|
||||||
|
function codeEsc(text, lang) {
|
||||||
|
if (!lang) return esc(text);
|
||||||
|
try { return Prism.highlight(text, Prism.languages[lang], lang); } catch (_) { return esc(text); }
|
||||||
|
}
|
||||||
|
function lineHtml(cls, oldNo, newNo, text, lang) {
|
||||||
return '<div class="vcs-line' + (cls ? ' ' + cls : '') + '"><span class="n">' + (oldNo == null ? '' : oldNo) +
|
return '<div class="vcs-line' + (cls ? ' ' + cls : '') + '"><span class="n">' + (oldNo == null ? '' : oldNo) +
|
||||||
'</span><span class="n">' + (newNo == null ? '' : newNo) + '</span><span class="c">' + esc(text) + '</span></div>';
|
'</span><span class="n">' + (newNo == null ? '' : newNo) + '</span><span class="c">' + codeEsc(text, lang) + '</span></div>';
|
||||||
}
|
}
|
||||||
|
|
||||||
// 行号自己推:@@ -a,b +c,d @@ 之后的上下文/+/- 分别推进两个计数器
|
// 行号自己推:@@ -a,b +c,d @@ 之后的上下文/+/- 分别推进两个计数器
|
||||||
@@ -86,6 +104,8 @@
|
|||||||
if (!f.patch) return '<div class="vcs-nodiff">没有可显示的差异</div>';
|
if (!f.patch) return '<div class="vcs-nodiff">没有可显示的差异</div>';
|
||||||
const out = [];
|
const out = [];
|
||||||
const lines = String(f.patch).split('\n');
|
const lines = String(f.patch).split('\n');
|
||||||
|
// 大 patch 不上色:逐行跑 Prism 是同步的,几千行会把面板卡一下
|
||||||
|
const lang = lines.length <= 2000 ? prismLang(f.path) : null;
|
||||||
let oldNo = 0, newNo = 0, inHunk = false, rows = 0;
|
let oldNo = 0, newNo = 0, inHunk = false, rows = 0;
|
||||||
for (let i = 0; i < lines.length; i++) {
|
for (let i = 0; i < lines.length; i++) {
|
||||||
const line = lines[i];
|
const line = lines[i];
|
||||||
@@ -99,9 +119,9 @@
|
|||||||
if (!inHunk) continue; // 文件头(diff --git / index / --- / +++)由文件行本身表达,不重复渲染
|
if (!inHunk) continue; // 文件头(diff --git / index / --- / +++)由文件行本身表达,不重复渲染
|
||||||
if (line.charAt(0) === '\\') { out.push('<div class="vcs-line meta"><span class="n"></span><span class="n"></span><span class="c">' + esc(line) + '</span></div>'); continue; }
|
if (line.charAt(0) === '\\') { out.push('<div class="vcs-line meta"><span class="n"></span><span class="n"></span><span class="c">' + esc(line) + '</span></div>'); continue; }
|
||||||
const c = line.charAt(0);
|
const c = line.charAt(0);
|
||||||
if (c === '+') out.push(lineHtml('a', null, newNo++, line.slice(1)));
|
if (c === '+') out.push(lineHtml('a', null, newNo++, line.slice(1), lang));
|
||||||
else if (c === '-') out.push(lineHtml('d', oldNo++, null, line.slice(1)));
|
else if (c === '-') out.push(lineHtml('d', oldNo++, null, line.slice(1), lang));
|
||||||
else out.push(lineHtml('', oldNo++, newNo++, line.slice(1)));
|
else out.push(lineHtml('', oldNo++, newNo++, line.slice(1), lang));
|
||||||
if (++rows > 3000) { out.push('<div class="vcs-nodiff">行数过多,剩余部分已隐藏</div>'); break; }
|
if (++rows > 3000) { out.push('<div class="vcs-nodiff">行数过多,剩余部分已隐藏</div>'); break; }
|
||||||
}
|
}
|
||||||
return out.join('') || '<div class="vcs-nodiff">仅改名或模式变更,没有内容差异</div>';
|
return out.join('') || '<div class="vcs-nodiff">仅改名或模式变更,没有内容差异</div>';
|
||||||
@@ -116,10 +136,21 @@
|
|||||||
'<span class="vcs-badge ' + esc(String(f.status || '').toLowerCase()) + '">' + esc(BADGE[f.status] || f.status) + '</span>' +
|
'<span class="vcs-badge ' + esc(String(f.status || '').toLowerCase()) + '">' + esc(BADGE[f.status] || f.status) + '</span>' +
|
||||||
'<span class="vcs-stat"><b class="a">+' + f.adds + '</b><b class="d">-' + f.dels + '</b></span>' +
|
'<span class="vcs-stat"><b class="a">+' + f.adds + '</b><b class="d">-' + f.dels + '</b></span>' +
|
||||||
'</div>' +
|
'</div>' +
|
||||||
'<div class="vcs-fb">' + patchHtml(f) + (f.truncated ? '<div class="vcs-nodiff">差异过大,已截断</div>' : '') + '</div>' +
|
'<div class="vcs-fb"><div class="vcs-fb-in">' + patchHtml(f) + (f.truncated ? '<div class="vcs-nodiff">差异过大,已截断</div>' : '') + '</div></div>' +
|
||||||
'</div>';
|
'</div>';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 行背景要盖满「可视宽度 ∩ 内容宽度」:只量 clientWidth 不够,长行溢出到 1129 时行背景仍只有 699,
|
||||||
|
// 横滑右边就露白。scrollWidth 正好是最长行的内容宽,取两者较大值写成 px 给内层。
|
||||||
|
function syncPatchWidth(scope) {
|
||||||
|
(scope || document).querySelectorAll('.vcs-fb').forEach(function (fb) {
|
||||||
|
const inner = fb.firstElementChild;
|
||||||
|
if (!inner) return;
|
||||||
|
const w = Math.max(fb.clientWidth, fb.scrollWidth);
|
||||||
|
if (w > 0) inner.style.minWidth = w + 'px';
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
function renderDetail(d) {
|
function renderDetail(d) {
|
||||||
st.cur = d;
|
st.cur = d;
|
||||||
const openAll = d.files.length <= 3; // 少量文件默认展开,多文件默认折叠
|
const openAll = d.files.length <= 3; // 少量文件默认展开,多文件默认折叠
|
||||||
@@ -143,6 +174,7 @@
|
|||||||
if (!d.files.length) parts.push('<div class="vcs-empty">没有文件变动</div>');
|
if (!d.files.length) parts.push('<div class="vcs-empty">没有文件变动</div>');
|
||||||
parts.push('</div>');
|
parts.push('</div>');
|
||||||
bodyEl().innerHTML = parts.join('');
|
bodyEl().innerHTML = parts.join('');
|
||||||
|
syncPatchWidth(bodyEl());
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------- 数据加载 ----------
|
// ---------- 数据加载 ----------
|
||||||
@@ -234,7 +266,7 @@
|
|||||||
const back = e.target.closest('.vcs-back');
|
const back = e.target.closest('.vcs-back');
|
||||||
if (back) { loadList(false); return; }
|
if (back) { loadList(false); return; }
|
||||||
const fh = e.target.closest('.vcs-fh');
|
const fh = e.target.closest('.vcs-fh');
|
||||||
if (fh) { fh.parentNode.classList.toggle('open'); return; }
|
if (fh) { fh.parentNode.classList.toggle('open'); syncPatchWidth(fh.parentNode); return; }
|
||||||
});
|
});
|
||||||
|
|
||||||
window.openVcsPane = openPane;
|
window.openVcsPane = openPane;
|
||||||
|
|||||||
@@ -36,6 +36,11 @@
|
|||||||
const MAX_MS = 180000; // 单次录音上限(流式上传后不再受 60s 限制)
|
const MAX_MS = 180000; // 单次录音上限(流式上传后不再受 60s 限制)
|
||||||
const MIN_MS = 500; // 短于这个时长按误触处理,不上传
|
const MIN_MS = 500; // 短于这个时长按误触处理,不上传
|
||||||
const FLUSH_MS = 60000; // 松手后等尾段识别完的上限(超过就当失败)
|
const FLUSH_MS = 60000; // 松手后等尾段识别完的上限(超过就当失败)
|
||||||
|
// 桌面用鼠标就用「点一下开始、再点一下发送」;手机(触屏)继续按住说话。
|
||||||
|
// 桌面一直压着鼠标键说话手累,上滑取消也没意义;两个平台各自按自己的习惯来。
|
||||||
|
const POINT_FINE = !!(window.matchMedia && window.matchMedia('(hover: hover) and (pointer: fine)').matches);
|
||||||
|
const HOLD_IDLE = POINT_FINE ? '点击 说话' : '按住 说话';
|
||||||
|
const HOLD_REC = POINT_FINE ? '说完 点击发送' : '松开 结束';
|
||||||
// 转写请求的并发上限:段一碎(6s 软切)并发就会很多,全放出去会把上游压垮、
|
// 转写请求的并发上限:段一碎(6s 软切)并发就会很多,全放出去会把上游压垮、
|
||||||
// 也可能被限流。超过就排到后面,等前面的落定再发。改完刷新页面即生效。
|
// 也可能被限流。超过就排到后面,等前面的落定再发。改完刷新页面即生效。
|
||||||
const ASR_MAX_CONCURRENCY = 3;
|
const ASR_MAX_CONCURRENCY = 3;
|
||||||
@@ -125,10 +130,14 @@
|
|||||||
// ---------- 遮罩 / 声波 ----------
|
// ---------- 遮罩 / 声波 ----------
|
||||||
function setOverlayMode(m) { // 'send' | 'cancel' | 'busy'
|
function setOverlayMode(m) { // 'send' | 'cancel' | 'busy'
|
||||||
cancelArmed = m === 'cancel';
|
cancelArmed = m === 'cancel';
|
||||||
if (overlay) overlay.classList.toggle('cancel', m === 'cancel');
|
if (overlay) {
|
||||||
|
overlay.classList.toggle('cancel', m === 'cancel');
|
||||||
|
overlay.classList.toggle('busy', m === 'busy'); // 识别中把操作行藏起来,避免空点
|
||||||
|
}
|
||||||
if (hintEl) {
|
if (hintEl) {
|
||||||
hintEl.textContent = m === 'cancel' ? '松开取消'
|
hintEl.textContent = m === 'cancel' ? '松手取消'
|
||||||
: m === 'busy' ? busyHintText() : '松手传送,上滑取消';
|
: m === 'busy' ? busyHintText()
|
||||||
|
: (POINT_FINE ? '' : '松手传送,上滑取消');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -302,7 +311,7 @@
|
|||||||
abortStream();
|
abortStream();
|
||||||
if (stopTimer) { clearTimeout(stopTimer); stopTimer = null; }
|
if (stopTimer) { clearTimeout(stopTimer); stopTimer = null; }
|
||||||
hold.classList.remove('recording');
|
hold.classList.remove('recording');
|
||||||
setHoldText('按住 说话');
|
setHoldText(HOLD_IDLE);
|
||||||
hideOverlay();
|
hideOverlay();
|
||||||
updateSendBtn();
|
updateSendBtn();
|
||||||
}
|
}
|
||||||
@@ -344,7 +353,7 @@
|
|||||||
segSent = 0;
|
segSent = 0;
|
||||||
segDone = 0;
|
segDone = 0;
|
||||||
hold.classList.add('recording');
|
hold.classList.add('recording');
|
||||||
setHoldText('松开 结束');
|
setHoldText(HOLD_REC);
|
||||||
showOverlay();
|
showOverlay();
|
||||||
|
|
||||||
if (native) {
|
if (native) {
|
||||||
@@ -413,7 +422,7 @@
|
|||||||
if (held < MIN_MS) discard = true;
|
if (held < MIN_MS) discard = true;
|
||||||
phase = 'busy';
|
phase = 'busy';
|
||||||
hold.classList.remove('recording');
|
hold.classList.remove('recording');
|
||||||
setHoldText(discard ? '按住 说话' : '正在识别…');
|
setHoldText(discard ? HOLD_IDLE : '正在识别…');
|
||||||
// 遮罩留着,文案换成动态识别进度;柱子停在低位,等结果回来再收
|
// 遮罩留着,文案换成动态识别进度;柱子停在低位,等结果回来再收
|
||||||
setOverlayMode(discard ? 'send' : 'busy');
|
setOverlayMode(discard ? 'send' : 'busy');
|
||||||
stopMeter();
|
stopMeter();
|
||||||
@@ -464,15 +473,15 @@
|
|||||||
resetUI();
|
resetUI();
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------- 按住 / 滑动 / 松开 ----------
|
// ---------- 按住 / 滑动 / 松开(手机)或点击切换(桌面)----------
|
||||||
hold.addEventListener('pointerdown', function (e) {
|
function onPointerDown(e) {
|
||||||
if (e && e.button != null && e.button !== 0) return; // 只响应左键/触摸
|
if (e && e.button != null && e.button !== 0) return; // 只响应左键/触摸
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
if (phase !== 'idle') return;
|
if (phase !== 'idle') return;
|
||||||
pressY = e.clientY || 0;
|
pressY = e.clientY || 0;
|
||||||
try { hold.setPointerCapture(e.pointerId); } catch (_) { /* 忽略 */ }
|
try { hold.setPointerCapture(e.pointerId); } catch (_) { /* 忽略 */ }
|
||||||
startHold();
|
startHold();
|
||||||
});
|
}
|
||||||
|
|
||||||
function onMove(e) {
|
function onMove(e) {
|
||||||
if (!pressing) return;
|
if (!pressing) return;
|
||||||
@@ -503,6 +512,16 @@
|
|||||||
else if (phase === 'arming') cancelHold(); // 还没真正开录:当误触
|
else if (phase === 'arming') cancelHold(); // 还没真正开录:当误触
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (POINT_FINE) {
|
||||||
|
// 桌面:点一下开始,再点一下发送(pressing 由 startHold 置 true 后一直保持,不会自己松)
|
||||||
|
hold.addEventListener('click', function (e) {
|
||||||
|
e.preventDefault();
|
||||||
|
if (phase === 'idle') startHold();
|
||||||
|
else if (phase === 'recording') finishHold();
|
||||||
|
else if (phase === 'arming') cancelHold(); // 等麦克风授权时再点一下 = 取消
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
hold.addEventListener('pointerdown', onPointerDown);
|
||||||
hold.addEventListener('pointerup', onRelease);
|
hold.addEventListener('pointerup', onRelease);
|
||||||
hold.addEventListener('pointercancel', onRelease);
|
hold.addEventListener('pointercancel', onRelease);
|
||||||
hold.addEventListener('pointermove', onMove);
|
hold.addEventListener('pointermove', onMove);
|
||||||
@@ -510,6 +529,22 @@
|
|||||||
window.addEventListener('pointerup', onRelease);
|
window.addEventListener('pointerup', onRelease);
|
||||||
window.addEventListener('pointercancel', onRelease);
|
window.addEventListener('pointercancel', onRelease);
|
||||||
window.addEventListener('pointermove', onMove);
|
window.addEventListener('pointermove', onMove);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 桌面点击模式:遮罩底部那行「取消 / 发送」的点击绑定
|
||||||
|
if (POINT_FINE) {
|
||||||
|
const sendBtn = $('voice-send');
|
||||||
|
const cancelBtn = $('voice-cancel');
|
||||||
|
if (sendBtn) sendBtn.addEventListener('click', function (e) { e.stopPropagation(); if (phase === 'recording') finishHold(); });
|
||||||
|
if (cancelBtn) cancelBtn.addEventListener('click', function (e) { e.stopPropagation(); cancelHold(); });
|
||||||
|
}
|
||||||
|
|
||||||
|
// 录音中 Esc 取消(两端都可用,桌面端尤其需要一个键盘出口)
|
||||||
|
document.addEventListener('keydown', function (e) {
|
||||||
|
if (e.key !== 'Escape' || phase === 'idle') return;
|
||||||
|
e.preventDefault();
|
||||||
|
cancelHold();
|
||||||
|
});
|
||||||
|
|
||||||
// 长按不弹系统菜单(移动端)
|
// 长按不弹系统菜单(移动端)
|
||||||
hold.addEventListener('contextmenu', function (e) { e.preventDefault(); });
|
hold.addEventListener('contextmenu', function (e) { e.preventDefault(); });
|
||||||
|
|||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
File diff suppressed because one or more lines are too long
+1
File diff suppressed because one or more lines are too long
+1
File diff suppressed because one or more lines are too long
@@ -81,10 +81,6 @@ router.post('/:id/files', upload.array('files', 10), function (req, res) {
|
|||||||
// 为什么不复用 GET /:id/files:那个接口同步递归整棵目录,会话里一旦有大项目 /
|
// 为什么不复用 GET /:id/files:那个接口同步递归整棵目录,会话里一旦有大项目 /
|
||||||
// node_modules,单线程 core 会被卡死(连 SSE 一起挂)。这里一律「一次一层」、
|
// node_modules,单线程 core 会被卡死(连 SSE 一起挂)。这里一律「一次一层」、
|
||||||
// 忽略大目录、限量返回,客户端展开才请求下一层。
|
// 忽略大目录、限量返回,客户端展开才请求下一层。
|
||||||
const TREE_IGNORE_DIRS = new Set([
|
|
||||||
'node_modules', '.git', 'dist', 'build', 'out', 'target', '.venv', 'venv',
|
|
||||||
'__pycache__', '.next', '.cache', 'coverage', '.idea', '.vscode',
|
|
||||||
]);
|
|
||||||
const TREE_MAX = 500;
|
const TREE_MAX = 500;
|
||||||
|
|
||||||
// 相对路径 → 会话根内的绝对路径。字面 + realpath 双重校验,防符号链接跳出会话目录。
|
// 相对路径 → 会话根内的绝对路径。字面 + realpath 双重校验,防符号链接跳出会话目录。
|
||||||
@@ -119,19 +115,21 @@ router.get('/:id/tree', function (req, res) {
|
|||||||
const childRel = rel ? rel + '/' + e.name : e.name;
|
const childRel = rel ? rel + '/' + e.name : e.name;
|
||||||
if (e.isSymbolicLink()) { entries.push({ name: e.name, rel: childRel, type: 'link' }); continue; }
|
if (e.isSymbolicLink()) { entries.push({ name: e.name, rel: childRel, type: 'link' }); continue; }
|
||||||
if (e.isDirectory()) {
|
if (e.isDirectory()) {
|
||||||
entries.push({ name: e.name, rel: childRel, type: 'dir', ignored: TREE_IGNORE_DIRS.has(e.name) });
|
// mtimeMs 给前端判断空目录是否还是空的:目录内增删子项会更新它
|
||||||
|
let mtimeMs = null;
|
||||||
|
try { mtimeMs = fs.statSync(path.join(abs, e.name)).mtimeMs; } catch (_) {}
|
||||||
|
entries.push({ name: e.name, rel: childRel, type: 'dir', mtimeMs: mtimeMs });
|
||||||
} else if (e.isFile()) {
|
} else if (e.isFile()) {
|
||||||
let size = null;
|
let size = null, mtimeMs = null;
|
||||||
try { size = fs.statSync(path.join(abs, e.name)).size; } catch (_) {}
|
try { const st = fs.statSync(path.join(abs, e.name)); size = st.size; mtimeMs = st.mtimeMs; } catch (_) {}
|
||||||
entries.push({ name: e.name, rel: childRel, type: 'file', size: size });
|
entries.push({ name: e.name, rel: childRel, type: 'file', size: size, mtimeMs: mtimeMs });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return res.status(500).json({ error: String((err && err.message) || err) });
|
return res.status(500).json({ error: String((err && err.message) || err) });
|
||||||
}
|
}
|
||||||
// 排序:正常目录 → 正常文件 → 被忽略的大目录(灰显沉底);同类按名称
|
// 排序:目录在前、文件在后;同类按名称
|
||||||
entries.sort((a, b) =>
|
entries.sort((a, b) =>
|
||||||
(a.ignored ? 1 : 0) - (b.ignored ? 1 : 0) ||
|
|
||||||
(a.type === 'dir' ? 0 : 1) - (b.type === 'dir' ? 0 : 1) ||
|
(a.type === 'dir' ? 0 : 1) - (b.type === 'dir' ? 0 : 1) ||
|
||||||
(a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
|
(a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
|
||||||
res.json({
|
res.json({
|
||||||
|
|||||||
@@ -14,6 +14,25 @@ const engine = require('../engine');
|
|||||||
|
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
|
|
||||||
|
// 这些接口都是弹宿主机的原生对话框 / 开 Finder / 开终端,只有坐在这台机器前才有意义。
|
||||||
|
// 远程访问(经隧道 / 反代 / 局域网)一律当作不存在,返回 404 —— 行为和服务器形态完全一致
|
||||||
|
// (那边 server.js 根本不挂这个路由),前端原有的 catch 就会把入口整条隐藏。
|
||||||
|
// 判断依据:反向代理一定会加 X-Forwarded-* 头(nginx 设的,tunnel client 原样转发),
|
||||||
|
// 本机直连 127.0.0.1:8090 不会有。
|
||||||
|
// 不能看 Host:tunnel client 用 fetch 转发时 Host 是禁止头、会被重写成 127.0.0.1:8090。
|
||||||
|
// 也不能看 X-Forwarded-For 的 IP 值:stream 分流后源地址永远是 127.0.0.1。
|
||||||
|
function isLocalHost(req) {
|
||||||
|
if (req.headers['x-forwarded-for'] || req.headers['x-forwarded-host']
|
||||||
|
|| req.headers['x-real-ip'] || req.headers['x-forwarded-proto']) return false;
|
||||||
|
const host = String(req.headers.host || '').replace(/:\d+$/, '').toLowerCase().replace(/^\[|\]$/g, '');
|
||||||
|
return host === '127.0.0.1' || host === 'localhost' || host === '::1';
|
||||||
|
}
|
||||||
|
|
||||||
|
router.use(function (req, res, next) {
|
||||||
|
if (isLocalHost(req)) return next();
|
||||||
|
res.status(404).json({ error: 'Not Found' });
|
||||||
|
});
|
||||||
|
|
||||||
function sendErr(res, err) {
|
function sendErr(res, err) {
|
||||||
const code = (err && err.status_code) || 500;
|
const code = (err && err.status_code) || 500;
|
||||||
res.status(code).json({ error: String((err && err.message) || err) });
|
res.status(code).json({ error: String((err && err.message) || err) });
|
||||||
|
|||||||
@@ -198,16 +198,16 @@ router.get('/:id', wrap((req, res) => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const taskDir = engine.taskDirOf(session.id);
|
|
||||||
// 定时任务状态(scheduler.js / schedule 工具;每会话至多一行,无则 null)。
|
// 定时任务状态(scheduler.js / schedule 工具;每会话至多一行,无则 null)。
|
||||||
// 列表接口故意不带此字段,避免 N+1;前端进会话详情时才拉。
|
// 列表接口故意不带此字段,避免 N+1;前端进会话详情时才拉。
|
||||||
const schedule = db.prepare(
|
const schedule = db.prepare(
|
||||||
'SELECT cron_expr, prompt, next_run_at, last_run_at, last_status, last_note FROM scheduled_tasks WHERE session_id = ?'
|
'SELECT cron_expr, prompt, next_run_at, last_run_at, last_status, last_note FROM scheduled_tasks WHERE session_id = ?'
|
||||||
).get(session.id) || null;
|
).get(session.id) || null;
|
||||||
|
// 不再返回 files:文件树由 /api/files 按目录懒加载(routes/files.js),
|
||||||
|
// 这里全量递归扫一遍纯属浪费——曾让每次切会话多传 1.4MB(10544 个文件)。
|
||||||
res.json({
|
res.json({
|
||||||
session,
|
session,
|
||||||
messages,
|
messages,
|
||||||
files: listTaskFiles(taskDir),
|
|
||||||
schedule,
|
schedule,
|
||||||
running: !!(engine.getRun(session.id) || {}).looping,
|
running: !!(engine.getRun(session.id) || {}).looping,
|
||||||
// 待投递队列(刷新/换设备后条幅能原样恢复):只在服务端内存里,重启即空
|
// 待投递队列(刷新/换设备后条幅能原样恢复):只在服务端内存里,重启即空
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ const wechat = require('./wechat');
|
|||||||
const llm = require('./llm');
|
const llm = require('./llm');
|
||||||
const mcp = require('./mcp');
|
const mcp = require('./mcp');
|
||||||
const skills = require('./tools/skills');
|
const skills = require('./tools/skills');
|
||||||
|
const shellBackend = require('./shell');
|
||||||
const log = require('./log');
|
const log = require('./log');
|
||||||
|
|
||||||
const cfg = loadConfig(process.env.AGENT_CONFIG);
|
const cfg = loadConfig(process.env.AGENT_CONFIG);
|
||||||
@@ -243,6 +244,10 @@ mcp.init(cfg).then(async () => {
|
|||||||
log.info('startup', ' auth=' + (auth.enabled ? 'login: ' + cfg.auth.users.map(u => u.user).join(', ') : '(disabled)'));
|
log.info('startup', ' auth=' + (auth.enabled ? 'login: ' + cfg.auth.users.map(u => u.user).join(', ') : '(disabled)'));
|
||||||
log.info('startup', ' wxbot=' + (cfg.wxbot.url && cfg.wxbot.token ? cfg.wxbot.url : '(未启用)'));
|
log.info('startup', ' wxbot=' + (cfg.wxbot.url && cfg.wxbot.token ? cfg.wxbot.url : '(未启用)'));
|
||||||
log.info('startup', ' log_level=' + cfg.log_level);
|
log.info('startup', ' log_level=' + cfg.log_level);
|
||||||
|
// 模型命令到底交给谁跑。硬定 shell 时这里是唯一的凭据(Windows 上尤其要看到);
|
||||||
|
// 探测不到就降成 warn——服务能起,但 terminal 工具会一片红。
|
||||||
|
if (shellBackend.resolve(cfg)) log.info('startup', ' terminal=' + shellBackend.describe(cfg));
|
||||||
|
else log.warn('startup', ' terminal=' + shellBackend.describe(cfg));
|
||||||
// 微信实例恢复 fire-and-forget:wxbot 没起只留日志,绝不阻塞/抛错影响启动。
|
// 微信实例恢复 fire-and-forget:wxbot 没起只留日志,绝不阻塞/抛错影响启动。
|
||||||
wechat.restore().catch(e => log.warn('wechat', '启动恢复异常:' + (e && e.message || e)));
|
wechat.restore().catch(e => log.warn('wechat', '启动恢复异常:' + (e && e.message || e)));
|
||||||
// prompt dump 失败不影响服务:只是核对用产物。
|
// prompt dump 失败不影响服务:只是核对用产物。
|
||||||
|
|||||||
@@ -0,0 +1,226 @@
|
|||||||
|
// 执行后端:全仓唯一处理「用哪个 shell 跑命令」「怎么杀整棵进程树」的地方。
|
||||||
|
//
|
||||||
|
// 为什么单开一层:POSIX 上 spawn('/bin/sh') + kill(-pid) 是刻意选的最强约束——
|
||||||
|
// /bin/sh 固定(不读 $SHELL,否则用户把 shell 设成 fish 后模型写的 POSIX 语法全废),
|
||||||
|
// 进程组让「停止」能一次带走模型起的孙进程(npm / python / ffmpeg 留下的才是麻烦)。
|
||||||
|
// Windows 没有 /bin/sh、没有进程组、也没有可发送的信号:同一个写法在那边从「有效」
|
||||||
|
// 变成「静默失效」,detached 还会多弹一个控制台。三种能力收敛成
|
||||||
|
// resolve / spawnShell / killTree,上层(terminal、skill、engine 取消)就不必出现平台分支。
|
||||||
|
//
|
||||||
|
// 默认行为与拆分前逐字节一致:不配任何 env 时仍是 /bin/sh -c + 进程组 +
|
||||||
|
// process.kill(-pid)。Windows 才走探测分支,探测不到就明确报错,绝不静默退回
|
||||||
|
// cmd.exe——cmd 的语法与模型写的 POSIX 差太远,静默降级只会让模型在报错里反复试错。
|
||||||
|
//
|
||||||
|
// 解析顺序(前面的赢,结果进程内缓存一次,与 config.js 的冷加载约定一致):
|
||||||
|
// 1. env AGENT_SHELL 显式指定可执行文件(绝对路径或 PATH 里的名字)
|
||||||
|
// 2. config.terminal.shell 同上,给不想碰 env 的部署方式
|
||||||
|
// 3. 自动探测 Windows:git-bash → busybox-w32 → 无
|
||||||
|
// POSIX :/bin/sh
|
||||||
|
// 4. env AGENT_SHELL_ARGS 覆盖参数模板(默认 -c,如 bash 想读 rc 可写 -lc)
|
||||||
|
// 另:env AGENT_GIT_BASH / AGENT_BUSYBOX 可指定各自的固定位置(便携安装用)。
|
||||||
|
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
const { spawn } = require('child_process');
|
||||||
|
|
||||||
|
const IS_WIN = process.platform === 'win32';
|
||||||
|
|
||||||
|
const INSTALL_HINT = IS_WIN
|
||||||
|
? 'Windows 需要 POSIX shell:装 Git for Windows(自带 bash),或把 busybox-w32 放到 local/bin/busybox.exe,'
|
||||||
|
+ '或用环境变量 AGENT_SHELL 指定 shell 路径'
|
||||||
|
: '需要 POSIX shell(/bin/sh 不存在)';
|
||||||
|
|
||||||
|
// MSYS(Git for Windows)默认会把「看起来像 Unix 路径」的参数改写成 Windows 路径
|
||||||
|
// (/c/foo → C:\foo)。模型的命令里 /tmp、/c、相对路径都可能被它悄悄改掉,
|
||||||
|
// 排查起来像"命令没生效"。关掉自动转换,让字节原样过去。
|
||||||
|
const MSYS_ENV = {
|
||||||
|
MSYS_NO_PATHCONV: '1', // Git for Windows 旧变量
|
||||||
|
MSYS2_ARG_CONV_EXCL: '*', // MSYS2 新变量
|
||||||
|
};
|
||||||
|
|
||||||
|
let cacheKey = null;
|
||||||
|
let cached; // 解析结果;null = 解析过但没有可用 shell
|
||||||
|
|
||||||
|
function trimStr(v) { return typeof v === 'string' ? v.trim() : ''; }
|
||||||
|
|
||||||
|
// 参数模板按 shell 习惯切成数组(支持引号),默认 ['-c']。
|
||||||
|
function splitArgs(s) {
|
||||||
|
const out = [];
|
||||||
|
let cur = '';
|
||||||
|
let quote = null;
|
||||||
|
for (const ch of String(s)) {
|
||||||
|
if (quote) { if (ch === quote) quote = null; else cur += ch; continue; }
|
||||||
|
if (ch === '"' || ch === "'") { quote = ch; continue; }
|
||||||
|
if (/\s/.test(ch)) { if (cur) { out.push(cur); cur = ''; } continue; }
|
||||||
|
cur += ch;
|
||||||
|
}
|
||||||
|
if (cur) out.push(cur);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function shellArgs() {
|
||||||
|
const custom = trimStr(process.env.AGENT_SHELL_ARGS);
|
||||||
|
return custom ? splitArgs(custom) : ['-c'];
|
||||||
|
}
|
||||||
|
|
||||||
|
function existsExec(p) {
|
||||||
|
try {
|
||||||
|
if (!fs.statSync(p).isFile()) return false;
|
||||||
|
if (!IS_WIN) fs.accessSync(p, fs.constants.X_OK);
|
||||||
|
return true;
|
||||||
|
} catch (_) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 自己遍历 PATH,不调 where.exe:少一次进程启动,也避开 where 的输出编码差异。
|
||||||
|
function whichWin(name) {
|
||||||
|
const exts = /\.\w+$/.test(name) ? [''] : ['', '.exe', '.cmd', '.bat'];
|
||||||
|
for (const dir of String(process.env.PATH || '').split(path.delimiter)) {
|
||||||
|
if (!dir) continue;
|
||||||
|
for (const ext of exts) {
|
||||||
|
const p = path.join(dir, name + ext);
|
||||||
|
if (existsExec(p)) return p;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Git for Windows 的 bash。C:\Windows\System32\bash.exe 是 WSL 启动器,明确排除:
|
||||||
|
// 它的 -c 之后是 Linux 命令,路径全在另一个文件系统里,拿它当 shell 会让每个命令都跑偏。
|
||||||
|
function findGitBash() {
|
||||||
|
const e = process.env;
|
||||||
|
const cands = [
|
||||||
|
e.AGENT_GIT_BASH,
|
||||||
|
e.ProgramFiles && path.join(e.ProgramFiles, 'Git', 'bin', 'bash.exe'),
|
||||||
|
e['ProgramFiles(x86)'] && path.join(e['ProgramFiles(x86)'], 'Git', 'bin', 'bash.exe'),
|
||||||
|
e.LOCALAPPDATA && path.join(e.LOCALAPPDATA, 'Programs', 'Git', 'bin', 'bash.exe'),
|
||||||
|
e.USERPROFILE && path.join(e.USERPROFILE, 'scoop', 'apps', 'git', 'current', 'bin', 'bash.exe'),
|
||||||
|
e.ProgramData && path.join(e.ProgramData, 'chocolatey', 'bin', 'bash.exe'),
|
||||||
|
whichWin('bash.exe'),
|
||||||
|
];
|
||||||
|
for (const c of cands) {
|
||||||
|
if (!c) continue;
|
||||||
|
if (/\\windows\\(system32|winsxs)\\/i.test(c) || /\\windowsapps\\/i.test(c)) continue;
|
||||||
|
if (existsExec(c)) return c;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// busybox-w32:单文件原生 exe(约 600KB),需要 `busybox sh -c` 的 applet 形式。
|
||||||
|
// 固定位置放在仓库 local/bin/,由启动器下载——不进系统 PATH,卸载即净。
|
||||||
|
function findBusybox() {
|
||||||
|
const e = process.env;
|
||||||
|
const cands = [
|
||||||
|
e.AGENT_BUSYBOX,
|
||||||
|
path.join(__dirname, '..', '..', 'local', 'bin', 'busybox.exe'),
|
||||||
|
whichWin('busybox.exe'),
|
||||||
|
];
|
||||||
|
for (const c of cands) {
|
||||||
|
if (c && existsExec(c)) return c;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function posixDefault() {
|
||||||
|
return { cmd: '/bin/sh', args: shellArgs(), kind: 'sh', source: 'default', env: null, detached: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
function fromExplicit(p) {
|
||||||
|
const args = shellArgs();
|
||||||
|
const busybox = /busybox/i.test(path.basename(p));
|
||||||
|
return {
|
||||||
|
cmd: p,
|
||||||
|
// busybox 是多 applet 单文件:必须点名 sh,否则 argv[0] 是 busybox 时它会当自己的子命令解析。
|
||||||
|
args: busybox ? ['sh', ...args] : args,
|
||||||
|
kind: busybox ? 'busybox' : 'bash',
|
||||||
|
source: 'explicit',
|
||||||
|
env: IS_WIN ? MSYS_ENV : null,
|
||||||
|
// POSIX 必须 detached(进程组是 killTree 的抓手);Windows 上开 detached 会新建控制台
|
||||||
|
// 并让子进程脱离 taskkill /T 的父子树,所以那边明确关掉。
|
||||||
|
detached: !IS_WIN,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function detectWindows() {
|
||||||
|
const bash = findGitBash();
|
||||||
|
if (bash) {
|
||||||
|
return { cmd: bash, args: shellArgs(), kind: 'bash', source: 'git-bash', env: MSYS_ENV, detached: false };
|
||||||
|
}
|
||||||
|
const bb = findBusybox();
|
||||||
|
if (bb) {
|
||||||
|
return { cmd: bb, args: ['sh', ...shellArgs()], kind: 'busybox', source: 'busybox-w32', env: null, detached: false };
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function detect(cfg) {
|
||||||
|
const explicit = trimStr(process.env.AGENT_SHELL)
|
||||||
|
|| trimStr(cfg && cfg.terminal && cfg.terminal.shell);
|
||||||
|
if (explicit) return fromExplicit(explicit);
|
||||||
|
if (!IS_WIN) return posixDefault();
|
||||||
|
return detectWindows();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 解析结果(对象形态,含 cmd/args/kind/source/env/detached)。没有可用 shell 时返回 null。
|
||||||
|
// 缓存键跟着「显式指定」的三个来源走:同一个进程里 cfg 或 env 变了会重新探测,
|
||||||
|
// 避免第一次调用(可能没有 cfg,比如技能层)把结果钉死。
|
||||||
|
function resolve(cfg) {
|
||||||
|
const key = [
|
||||||
|
trimStr(process.env.AGENT_SHELL),
|
||||||
|
trimStr(process.env.AGENT_SHELL_ARGS),
|
||||||
|
trimStr(cfg && cfg.terminal && cfg.terminal.shell),
|
||||||
|
].join('\u0000');
|
||||||
|
if (cacheKey !== key) {
|
||||||
|
cacheKey = key;
|
||||||
|
cached = detect(cfg);
|
||||||
|
}
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 重新探测(测试与「改完立即生效」用;正常运行不需要调)。
|
||||||
|
function reset() { cacheKey = null; cached = undefined; }
|
||||||
|
|
||||||
|
function spawnShell(cfg, command, opts) {
|
||||||
|
const o = opts || {};
|
||||||
|
const sh = resolve(cfg);
|
||||||
|
if (!sh) throw new Error('执行后端不可用:' + INSTALL_HINT);
|
||||||
|
const env = sh.env ? { ...process.env, ...sh.env, ...(o.env || {}) } : { ...process.env, ...(o.env || {}) };
|
||||||
|
return spawn(sh.cmd, [...sh.args, String(command)], {
|
||||||
|
cwd: o.cwd,
|
||||||
|
env,
|
||||||
|
detached: sh.detached,
|
||||||
|
// 仅 Windows 生效:detached 之外的第二道保险,避免每条命令弹一个控制台窗口。
|
||||||
|
windowsHide: true,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 杀整棵进程树。POSIX 走进程组(原来那两行原样保留);Windows 没有进程组,
|
||||||
|
// 用 taskkill /T 按父子树杀——不能用 child.kill(),那只会杀 shell 本身,
|
||||||
|
// 模型起的 node/python/ffmpeg 孙进程会留下来继续占端口。
|
||||||
|
function killTree(child) {
|
||||||
|
if (!child || !child.pid) return false;
|
||||||
|
if (!IS_WIN) {
|
||||||
|
try { process.kill(-child.pid, 'SIGKILL'); return true; } catch (_) {
|
||||||
|
try { child.kill('SIGKILL'); return true; } catch (__) { return false; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const p = spawn('taskkill', ['/T', '/F', '/PID', String(child.pid)], { stdio: 'ignore', windowsHide: true });
|
||||||
|
p.on('error', () => {});
|
||||||
|
p.unref();
|
||||||
|
return true;
|
||||||
|
} catch (_) {
|
||||||
|
try { child.kill(); return true; } catch (__) { return false; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 一行诊断(启动日志 / 健康检查用):告诉人「模型命令到底交给谁跑」。
|
||||||
|
function describe(cfg) {
|
||||||
|
const sh = resolve(cfg);
|
||||||
|
if (!sh) return '未找到(' + INSTALL_HINT + ')';
|
||||||
|
const args = sh.args.join(' ');
|
||||||
|
return sh.cmd + ' ' + args + ' ← ' + sh.source;
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { resolve, reset, spawnShell, killTree, describe, INSTALL_HINT };
|
||||||
+43
-3
@@ -5,6 +5,31 @@ function createBus() {
|
|||||||
const clients = new Map(); // session_id -> Set<res>
|
const clients = new Map(); // session_id -> Set<res>
|
||||||
const internal = new Set(); // fn(sessionId, event, data)
|
const internal = new Set(); // fn(sessionId, event, data)
|
||||||
|
|
||||||
|
// 高频事件的合并缓冲:LLM 每吐一个 token 就是一条 assistant_delta,一次 res.write 就是一个
|
||||||
|
// TCP 包(Node 默认 TCP_NODELAY)。手机热点 / 跨境链路上包数比字节数更伤——每包都要射频调度,
|
||||||
|
// 拥塞窗口也容易被小包拖住。摍 50ms 或 8 条合并成一次 write。
|
||||||
|
// 其他事件立即发,但发前先 flush,保证前端看到的顺序和产生顺序一致。
|
||||||
|
const MERGE_EVENTS = new Set(['assistant_delta', 'reasoning_delta', 'tool_call_args']);
|
||||||
|
const FLUSH_MS = 50;
|
||||||
|
const FLUSH_COUNT = 8;
|
||||||
|
const pending = new Map(); // session_id -> { parts: string[], timer }
|
||||||
|
|
||||||
|
function writeAll(sessionId, payload) {
|
||||||
|
const set = clients.get(sessionId);
|
||||||
|
if (!set || set.size === 0) return;
|
||||||
|
for (const res of Array.from(set)) {
|
||||||
|
try { res.write(payload); } catch (_) { removeClient(sessionId, res); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function flush(sessionId) {
|
||||||
|
const p = pending.get(sessionId);
|
||||||
|
if (!p) return;
|
||||||
|
pending.delete(sessionId);
|
||||||
|
if (p.timer) { clearTimeout(p.timer); p.timer = null; }
|
||||||
|
if (p.parts.length) writeAll(sessionId, p.parts.join(''));
|
||||||
|
}
|
||||||
|
|
||||||
function onInternal(fn) {
|
function onInternal(fn) {
|
||||||
internal.add(fn);
|
internal.add(fn);
|
||||||
return () => internal.delete(fn);
|
return () => internal.delete(fn);
|
||||||
@@ -19,7 +44,10 @@ function createBus() {
|
|||||||
const set = clients.get(sessionId);
|
const set = clients.get(sessionId);
|
||||||
if (!set) return;
|
if (!set) return;
|
||||||
set.delete(res);
|
set.delete(res);
|
||||||
if (set.size === 0) clients.delete(sessionId);
|
if (set.size === 0) {
|
||||||
|
clients.delete(sessionId);
|
||||||
|
flush(sessionId); // 没人看了,把还摍着的清掉,避免 pending 常驻
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// event 名称 + 任意 JSON data。无客户端时静默丢弃(消息本身已持久化,重连可回放)。
|
// event 名称 + 任意 JSON data。无客户端时静默丢弃(消息本身已持久化,重连可回放)。
|
||||||
@@ -32,13 +60,25 @@ function createBus() {
|
|||||||
}
|
}
|
||||||
const set = clients.get(sessionId);
|
const set = clients.get(sessionId);
|
||||||
if (!set || set.size === 0) return;
|
if (!set || set.size === 0) return;
|
||||||
|
|
||||||
const payload = 'event: ' + event + '\ndata: ' + JSON.stringify(data) + '\n\n';
|
const payload = 'event: ' + event + '\ndata: ' + JSON.stringify(data) + '\n\n';
|
||||||
for (const res of Array.from(set)) {
|
|
||||||
try { res.write(payload); } catch (_) { removeClient(sessionId, res); }
|
if (MERGE_EVENTS.has(event)) {
|
||||||
|
let p = pending.get(sessionId);
|
||||||
|
if (!p) { p = { parts: [], timer: null }; pending.set(sessionId, p); }
|
||||||
|
p.parts.push(payload);
|
||||||
|
if (p.parts.length >= FLUSH_COUNT) { flush(sessionId); return; }
|
||||||
|
if (!p.timer) p.timer = setTimeout(() => flush(sessionId), FLUSH_MS);
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 非合并事件:先把摍着的发掉,保证顺序不乱
|
||||||
|
flush(sessionId);
|
||||||
|
writeAll(sessionId, payload);
|
||||||
}
|
}
|
||||||
|
|
||||||
function closeAll(sessionId) {
|
function closeAll(sessionId) {
|
||||||
|
flush(sessionId);
|
||||||
const set = clients.get(sessionId);
|
const set = clients.get(sessionId);
|
||||||
if (!set) return;
|
if (!set) return;
|
||||||
for (const res of Array.from(set)) {
|
for (const res of Array.from(set)) {
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ const path = require('path');
|
|||||||
const net = require('net'); // fetch SSRF 防护:IP 字面量/解析结果判私网
|
const net = require('net'); // fetch SSRF 防护:IP 字面量/解析结果判私网
|
||||||
const dns = require('dns').promises; // 同上:主机名 → IP 后统一判定
|
const dns = require('dns').promises; // 同上:主机名 → IP 后统一判定
|
||||||
const fsp = require('fs').promises;
|
const fsp = require('fs').promises;
|
||||||
const { spawn } = require('child_process');
|
const shell = require('../shell'); // 执行后端:shell 解析 + 进程树 kill(平台差异只在那边,这里不做分支)
|
||||||
const mcp = require('../mcp');
|
const mcp = require('../mcp');
|
||||||
const skills = require('./skills');
|
const skills = require('./skills');
|
||||||
const Database = require('better-sqlite3'); // db 工具:会话目录下的 data.db(同步 API,与单进程模型契合)
|
const Database = require('better-sqlite3'); // db 工具:会话目录下的 data.db(同步 API,与单进程模型契合)
|
||||||
@@ -764,7 +764,7 @@ function selectOutput(text, head, tail) {
|
|||||||
return parts.join('\n\n');
|
return parts.join('\n\n');
|
||||||
}
|
}
|
||||||
|
|
||||||
// terminal:spawn + 进程组 kill + 超时 + 输出截断
|
// terminal:交执行后端起 shell(POSIX 默认 /bin/sh -c,Windows 由 shell.js 探测)+ 超时 + 输出截断
|
||||||
// 通用终端输出 UI 卡片通道:命令行尾部的 ::ui_card {json}:: 标记行 → 从模型面剥离,整块交 ctx.onCard
|
// 通用终端输出 UI 卡片通道:命令行尾部的 ::ui_card {json}:: 标记行 → 从模型面剥离,整块交 ctx.onCard
|
||||||
// (与 MCP 回包 ui_card 块同一协议,见 mcp.js:任何命令行都可产卡,不限 officecli 封装层)。
|
// (与 MCP 回包 ui_card 块同一协议,见 mcp.js:任何命令行都可产卡,不限 officecli 封装层)。
|
||||||
// JSON 解析失败/无 action/ctx 不带 onCard 时标记行原样保留(宁可见不丢数据)。
|
// JSON 解析失败/无 action/ctx 不带 onCard 时标记行原样保留(宁可见不丢数据)。
|
||||||
@@ -809,7 +809,7 @@ async function toolTerminal(ctx, args) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return new Promise((resolve) => {
|
return new Promise((resolve) => {
|
||||||
const child = spawn('/bin/sh', ['-c', args.command], { cwd, detached: true, env: process.env });
|
const child = shell.spawnShell(cfg, args.command, { cwd });
|
||||||
ctx.run.procs.add(child);
|
ctx.run.procs.add(child);
|
||||||
let out = '';
|
let out = '';
|
||||||
let killedBy = null; // 'timeout' | 'cancelled'
|
let killedBy = null; // 'timeout' | 'cancelled'
|
||||||
@@ -853,10 +853,8 @@ async function toolTerminal(ctx, args) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function killGroup(child) {
|
function killGroup(child) {
|
||||||
if (!child.pid) return;
|
// 平台差异交给执行后端:POSIX 杀进程组,Windows 走 taskkill /T 杀进程树。
|
||||||
try { process.kill(-child.pid, 'SIGKILL'); } catch (_) {
|
shell.killTree(child);
|
||||||
try { child.kill('SIGKILL'); } catch (__) {}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// fetch:抓取并转 Markdown。超时/取消覆盖到 body 读取完成(非仅响应头);
|
// fetch:抓取并转 Markdown。超时/取消覆盖到 body 读取完成(非仅响应头);
|
||||||
@@ -1757,7 +1755,7 @@ function toolRecall(ctx, args) {
|
|||||||
case 'search': {
|
case 'search': {
|
||||||
const q = String(args.query || '').trim();
|
const q = String(args.query || '').trim();
|
||||||
if (!q) throw new Error('op=search 需要 query(关键词;空格分隔多个词更好,如「身份证 水印」)');
|
if (!q) throw new Error('op=search 需要 query(关键词;空格分隔多个词更好,如「身份证 水印」)');
|
||||||
const txt = memory.searchFragments(db, user, q, args.count);
|
const txt = memory.searchFragments(db, user, q, args.count, ctx.sessionId);
|
||||||
return txt || '日记中无「' + q + '」相关记录。';
|
return txt || '日记中无「' + q + '」相关记录。';
|
||||||
}
|
}
|
||||||
case 'days': {
|
case 'days': {
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ const { spawn } = require('child_process');
|
|||||||
const YAML = require('yaml');
|
const YAML = require('yaml');
|
||||||
const log = require('../log');
|
const log = require('../log');
|
||||||
const rexec = require('../remote-exec');
|
const rexec = require('../remote-exec');
|
||||||
|
const shell = require('../shell'); // 本地 spawn 技能时的进程树 kill(平台差异只在 shell.js)
|
||||||
// mode=skill 的 MCP 工具在 get/run 时由 core 直接转发;mcp.js 只依赖 ./log,不成环。
|
// mode=skill 的 MCP 工具在 get/run 时由 core 直接转发;mcp.js 只依赖 ./log,不成环。
|
||||||
const mcp = require('../mcp');
|
const mcp = require('../mcp');
|
||||||
|
|
||||||
@@ -187,7 +188,8 @@ function runEntry(ctx, entry, args, cwd, timeoutMs) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
const child = spawn(entry, args, { cwd, env: process.env, detached: true });
|
// windowsHide:Windows 上 detached 之外的第二道保险,避免弹控制台;POSIX 忽略该选项。
|
||||||
|
const child = spawn(entry, args, { cwd, env: process.env, detached: true, windowsHide: true });
|
||||||
if (ctx.run && ctx.run.procs) ctx.run.procs.add(child);
|
if (ctx.run && ctx.run.procs) ctx.run.procs.add(child);
|
||||||
let out = '';
|
let out = '';
|
||||||
let settled = false;
|
let settled = false;
|
||||||
@@ -200,7 +202,7 @@ function runEntry(ctx, entry, args, cwd, timeoutMs) {
|
|||||||
settled = true;
|
settled = true;
|
||||||
clearInterval(cancelCheck);
|
clearInterval(cancelCheck);
|
||||||
if (ctx.run && ctx.run.procs) ctx.run.procs.delete(child);
|
if (ctx.run && ctx.run.procs) ctx.run.procs.delete(child);
|
||||||
try { process.kill(-child.pid, 'SIGKILL'); } catch (_) { try { child.kill('SIGKILL'); } catch (__) {} }
|
shell.killTree(child);
|
||||||
reject(new SkillExecutionError('技能执行超时(' + timeoutMs + 'ms)已终止:\n' + out.trim(), -1));
|
reject(new SkillExecutionError('技能执行超时(' + timeoutMs + 'ms)已终止:\n' + out.trim(), -1));
|
||||||
}, timeoutMs);
|
}, timeoutMs);
|
||||||
|
|
||||||
@@ -209,7 +211,7 @@ function runEntry(ctx, entry, args, cwd, timeoutMs) {
|
|||||||
settled = true;
|
settled = true;
|
||||||
clearTimeout(timer);
|
clearTimeout(timer);
|
||||||
if (ctx.run && ctx.run.procs) ctx.run.procs.delete(child);
|
if (ctx.run && ctx.run.procs) ctx.run.procs.delete(child);
|
||||||
try { process.kill(-child.pid, 'SIGKILL'); } catch (_) { try { child.kill('SIGKILL'); } catch (__) {} }
|
shell.killTree(child);
|
||||||
reject(new SkillExecutionError('技能执行被用户终止', -1));
|
reject(new SkillExecutionError('技能执行被用户终止', -1));
|
||||||
}
|
}
|
||||||
}, 200);
|
}, 200);
|
||||||
|
|||||||
@@ -63,6 +63,63 @@ cd agent
|
|||||||
这个页面是纯静态文件(不用起服务),所以“node 都没装”的时候也能打开。重跑脚本会重新生成;
|
这个页面是纯静态文件(不用起服务),所以“node 都没装”的时候也能打开。重跑脚本会重新生成;
|
||||||
即使没自动弹出,文件也一直在那个路径。
|
即使没自动弹出,文件也一直在那个路径。
|
||||||
|
|
||||||
|
## Windows
|
||||||
|
|
||||||
|
需要 Node 20+(不需要 Docker,也不需要装 Git):
|
||||||
|
|
||||||
|
```bat
|
||||||
|
node local\start-win.mjs
|
||||||
|
node local\start-win.mjs --workspace=D:\AgentWork --port=8090
|
||||||
|
```
|
||||||
|
|
||||||
|
首次运行会:
|
||||||
|
|
||||||
|
1. 自检 Node 版本
|
||||||
|
2. **找命令执行环境**:优先用已装的 Git for Windows(自带 bash);没有再自动下载
|
||||||
|
[busybox-w32](https://frippery.org/busybox)(单文件约 600KB)到 `local/bin/busybox.exe`
|
||||||
|
3. 建工作目录(默认 `%USERPROFILE%\AgentWork`,`--workspace` 可改)下的 `tasks/` `data/` `skills/`
|
||||||
|
4. 生成 `local/config.win.yml`(**首次生成,之后永不覆盖**)
|
||||||
|
5. 把仓库 `skills/` 里的内置技能补过去(只补缺不覆盖)
|
||||||
|
6. `app/node_modules` 缺失时 `npm install`
|
||||||
|
7. 起 core 并守护(退出 3 秒后自动重启,连崩 5 次停)
|
||||||
|
|
||||||
|
浏览器开 `http://127.0.0.1:8090`,到「设置 → 模型池」加平台和 API Key。
|
||||||
|
**停止:Ctrl+C**(没有 `stop.sh`,启动器就是前台进程)。`--check` 只做自检不启动。
|
||||||
|
|
||||||
|
### 为什么 Windows 是另一条代码路径
|
||||||
|
|
||||||
|
`start.sh` 靠 `lsof` / `pgrep` / `readlink -f` / `nohup` / `setsid` / 进程组信号,Windows 一个都没有。
|
||||||
|
所以那 1100 多行 bash 没有移植,而是用 Node 重写了「启动器」这一层——它本来就只做进程管理,
|
||||||
|
不需要 shell。**业务代码一行都不分平台**:平台差异只落在两个文件里:
|
||||||
|
|
||||||
|
| 文件 | 负责 |
|
||||||
|
|---|---|
|
||||||
|
| `app/server/shell.js` | 用哪个 shell 跑命令、怎么杀进程树(POSIX 进程组 / Windows `taskkill /T`) |
|
||||||
|
| `local/start-win.mjs` | 探测、下载 busybox、生成配置、起进程、守护 |
|
||||||
|
|
||||||
|
### 覆盖与排错
|
||||||
|
|
||||||
|
| 变量 | 作用 |
|
||||||
|
|---|---|
|
||||||
|
| `AGENT_SHELL` | 直接指定 shell(绝对路径或 PATH 名),跳过一切探测 |
|
||||||
|
| `AGENT_SHELL_ARGS` | 参数模板,默认 `-c`(如 bash 想读 rc 可写 `-lc`) |
|
||||||
|
| `AGENT_GIT_BASH` | 指定 git-bash 位置(便携版/非标准安装路径) |
|
||||||
|
| `AGENT_BUSYBOX` | 指定 busybox.exe 位置 |
|
||||||
|
| `AGENT_BUSYBOX_URL` | 换 busybox 下载源(国内网络) |
|
||||||
|
|
||||||
|
命令到底交给了谁跑:启动日志里有一行 `terminal=...`,失败时会写成 `terminal=未找到(...)`。
|
||||||
|
|
||||||
|
### Windows 上仍有的限制
|
||||||
|
|
||||||
|
- **四个同栈 MCP 没有自动拉起**(配置里 `mcp_servers: []`):网页搜索/图片/视频/语音暂不可用,
|
||||||
|
`terminal`、文件工具、技能正常。
|
||||||
|
- **office 预览网关没起**:docx/xlsx/pptx 不能在线预览,但 `office` 技能生成文件不受影响。
|
||||||
|
- **没有沙箱**:和 macOS/Linux 本地模式一样,AI 的 `terminal` 就是你的 shell,能读写你有权限的任何文件。
|
||||||
|
工作目录选专用的,别选 `C:\` 或整个仓库。
|
||||||
|
- **`chmod` / `ln -s` 这类不生效**:Windows 没有 POSIX 权限位;模型写这类命令会“成功但什么都没做”。
|
||||||
|
- **`/tmp` 不是 Linux 的 `/tmp`**:busybox 会把它当当前盘根目录(`C:\tmp`),git-bash 映射到 `%TEMP%`。
|
||||||
|
模型最好用相对路径或会话目录。
|
||||||
|
|
||||||
## 可选能力
|
## 可选能力
|
||||||
|
|
||||||
| 能力 | 需要 | 没有时的表现 |
|
| 能力 | 需要 | 没有时的表现 |
|
||||||
@@ -72,6 +129,7 @@ cd agent
|
|||||||
| Office 文档(docx/xlsx/pptx) | 首次用到时下载一次 officecli 二进制(约 34MB) | `office` 报 `binary missing` 并给出该技能 `AGENTS.md` 的路径,按它下载即可(不需 root、不需重启);预览面板里直接显示同一份安装说明 |
|
| Office 文档(docx/xlsx/pptx) | 首次用到时下载一次 officecli 二进制(约 34MB) | `office` 报 `binary missing` 并给出该技能 `AGENTS.md` 的路径,按它下载即可(不需 root、不需重启);预览面板里直接显示同一份安装说明 |
|
||||||
| 网页搜索 | 无 | 装了 Node 就有(内置免费后端) |
|
| 网页搜索 | 无 | 装了 Node 就有(内置免费后端) |
|
||||||
| 图片 / 视频生成 | 设置页给对应 MCP 填上游 key | 调用时报明确的缺参错误 |
|
| 图片 / 视频生成 | 设置页给对应 MCP 填上游 key | 调用时报明确的缺参错误 |
|
||||||
|
| 反向隧道 | `tunnel/client.yml`(服务器地址 + token) | `start.sh` 跳过,不占端口;配置说明见 `tunnel/README.md` |
|
||||||
|
|
||||||
装完 `ffmpeg` 之后**重跑一次 `./local/start.sh`** 即可生效。`python3` 稍特殊:技能清单本来就在,
|
装完 `ffmpeg` 之后**重跑一次 `./local/start.sh`** 即可生效。`python3` 稍特殊:技能清单本来就在,
|
||||||
只要新装的解释器落在 core 启动时 `PATH` 已包含的目录里(如 brew 的 `/opt/homebrew/bin`)就无需重启;
|
只要新装的解释器落在 core 启动时 `PATH` 已包含的目录里(如 brew 的 `/opt/homebrew/bin`)就无需重启;
|
||||||
@@ -144,6 +202,9 @@ git pull
|
|||||||
|
|
||||||
另外,`core` 只监听 `127.0.0.1`,同一局域网的人访问不到。
|
另外,`core` 只监听 `127.0.0.1`,同一局域网的人访问不到。
|
||||||
|
|
||||||
|
配了隧道后,core 会经隧道 client 暴露到公网域名。访问控制靠隧道 token + 上游 nginx 的 TLS;
|
||||||
|
入口仍是 `127.0.0.1:8090`,不额外监听端口。
|
||||||
|
|
||||||
## 已知限制
|
## 已知限制
|
||||||
|
|
||||||
- **没 ffmpeg 时 core 日志会有一条 `asr 工具发现失败`**:此时 `mcp_asr` 不启动(它转码要靠
|
- **没 ffmpeg 时 core 日志会有一条 `asr 工具发现失败`**:此时 `mcp_asr` 不启动(它转码要靠
|
||||||
|
|||||||
@@ -0,0 +1,324 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
// Windows 本机模式启动器(macOS / Linux 用 local/start.sh,两者注入同一组环境变量)。
|
||||||
|
//
|
||||||
|
// 为什么单独一个 Node 脚本:start.sh 那 1100 多行 bash 靠的是 lsof / pgrep / readlink -f /
|
||||||
|
// nohup / setsid / 进程组信号,Windows 一个都没有。与其在 Windows 上凑一套半残的 POSIX 环境,
|
||||||
|
// 不如用 Node 重写"启动器"这一层——它本来就只做进程管理,不需要 shell。
|
||||||
|
// 业务代码(app/server)一行都不分平台,平台差异只落在 app/server/shell.js 与这个文件里。
|
||||||
|
//
|
||||||
|
// 做的事,按顺序:
|
||||||
|
// 1. 自检(Node 20+)
|
||||||
|
// 2. 找 POSIX 命令执行环境:git-bash → 已有的 busybox-w32 → 都没有就下载 busybox-w32
|
||||||
|
// 3. 首次运行生成工作目录与 local/config.win.yml(之后永不覆盖)
|
||||||
|
// 4. 补技能(只补缺,不覆盖)
|
||||||
|
// 5. app/node_modules 缺失时 npm install
|
||||||
|
// 6. 拉起 core 并守护(退出自动重启)
|
||||||
|
//
|
||||||
|
// 用法:
|
||||||
|
// node local/start-win.mjs # 默认工作目录 %USERPROFILE%\AgentWork
|
||||||
|
// node local/start-win.mjs --workspace=D:\ai # 指定工作目录
|
||||||
|
// node local/start-win.mjs --check # 只做自检与探测,不启动
|
||||||
|
// node local/start-win.mjs --port=8090 --no-open
|
||||||
|
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import path from 'node:path';
|
||||||
|
import os from 'node:os';
|
||||||
|
import { spawn, spawnSync } from 'node:child_process';
|
||||||
|
import { createRequire } from 'node:module';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
|
const require = createRequire(import.meta.url);
|
||||||
|
const shellBackend = require('../app/server/shell.js');
|
||||||
|
|
||||||
|
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||||
|
const IS_WIN = process.platform === 'win32';
|
||||||
|
const BUSYBOX_PATH = path.join(ROOT, 'local', 'bin', 'busybox.exe');
|
||||||
|
const CONFIG_PATH = path.join(ROOT, 'local', 'config.win.yml');
|
||||||
|
|
||||||
|
// ---------- 小工具 ----------
|
||||||
|
const C = { ok: '\x1b[32m', warn: '\x1b[33m', err: '\x1b[31m', dim: '\x1b[2m', n: '\x1b[0m' };
|
||||||
|
const say = (s) => console.log(`${C.ok}==>${C.n} ${s}`);
|
||||||
|
const warn = (s) => console.log(`${C.warn}[!]${C.n} ${s}`);
|
||||||
|
const dim = (s) => console.log(`${C.dim} ${s}${C.n}`);
|
||||||
|
function die(s, hint) {
|
||||||
|
console.error(`${C.err}[x]${C.n} ${s}`);
|
||||||
|
if (hint) console.error(` ${hint}`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 参数 ----------
|
||||||
|
const opt = { workspace: '', port: 8090, open: true, check: false };
|
||||||
|
for (const a of process.argv.slice(2)) {
|
||||||
|
if (a.startsWith('--workspace=')) opt.workspace = a.slice('--workspace='.length);
|
||||||
|
else if (a.startsWith('--port=')) opt.port = Number(a.slice('--port='.length)) || 8090;
|
||||||
|
else if (a === '--no-open') opt.open = false;
|
||||||
|
else if (a === '--check') opt.check = true;
|
||||||
|
else if (a === '-h' || a === '--help') {
|
||||||
|
console.log('用法: node local/start-win.mjs [--workspace=<目录>] [--port=8090] [--no-open] [--check]');
|
||||||
|
process.exit(0);
|
||||||
|
} else die(`未知参数:${a}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 1. 自检 ----------
|
||||||
|
function checkNode() {
|
||||||
|
const major = Number(String(process.versions.node).split('.')[0]);
|
||||||
|
if (major < 20) die(`需要 Node.js 20+,当前 ${process.version}`, '装新版:https://nodejs.org/ 或 winget install OpenJS.NodeJS.LTS');
|
||||||
|
say(`Node ${process.version}(${process.arch})`);
|
||||||
|
if (!IS_WIN) warn('当前不是 Windows:这个启动器只是 Windows 用;macOS/Linux 请用 local/start.sh');
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 2. 命令执行环境 ----------
|
||||||
|
// 优先级由 app/server/shell.js 决定(AGENT_SHELL > 配置 > git-bash > busybox-w32)。
|
||||||
|
// 这里只负责"没有就补一个":装到 local/bin/busybox.exe,core 那边按固定路径探测得到。
|
||||||
|
async function ensureShell() {
|
||||||
|
shellBackend.reset();
|
||||||
|
const found = shellBackend.resolve({});
|
||||||
|
if (found) {
|
||||||
|
say(`命令执行环境:${shellBackend.describe({})}`);
|
||||||
|
return found;
|
||||||
|
}
|
||||||
|
if (!IS_WIN) die('找不到 POSIX shell(/bin/sh)', '这个启动器是 Windows 用的;macOS/Linux 用 local/start.sh');
|
||||||
|
|
||||||
|
warn('没有找到 POSIX shell(git-bash 与 busybox-w32 都不在)');
|
||||||
|
say('下载 busybox-w32(单文件,约 600KB,不需要管理员权限)');
|
||||||
|
await downloadBusybox();
|
||||||
|
|
||||||
|
shellBackend.reset();
|
||||||
|
const after = shellBackend.resolve({});
|
||||||
|
if (!after) die('busybox-w32 装好了但仍探测不到', `检查文件是否存在且可执行:${BUSYBOX_PATH}`);
|
||||||
|
say(`命令执行环境:${shellBackend.describe({})}`);
|
||||||
|
return after;
|
||||||
|
}
|
||||||
|
|
||||||
|
// busybox-w32 官方发布页永远指向同一个 busybox.exe;国内下载不顺时可自行换源。
|
||||||
|
// 全部候选都失败就明确报错并给出"手动放文件"的一步操作,不静默降级到 cmd.exe。
|
||||||
|
async function downloadBusybox() {
|
||||||
|
const urls = [];
|
||||||
|
if (process.env.AGENT_BUSYBOX_URL) urls.push(process.env.AGENT_BUSYBOX_URL);
|
||||||
|
urls.push('https://frippery.org/files/busybox/busybox.exe');
|
||||||
|
|
||||||
|
// 备用源:GitHub Release(release 资产名固定为 busybox.exe)。国内直连 GitHub 慢时
|
||||||
|
// 自动走 gh-proxy 前缀重试,两者都失败才放弃。
|
||||||
|
try {
|
||||||
|
const gh = await githubBusyboxUrl();
|
||||||
|
if (gh) urls.push(gh, 'https://gh-proxy.com/' + gh);
|
||||||
|
} catch (_) { /* 拿不到 latest 就只试官方源 */ }
|
||||||
|
|
||||||
|
fs.mkdirSync(path.dirname(BUSYBOX_PATH), { recursive: true });
|
||||||
|
const tmp = BUSYBOX_PATH + '.download';
|
||||||
|
let lastErr = '';
|
||||||
|
for (const u of urls) {
|
||||||
|
try {
|
||||||
|
process.stdout.write(` ${u}\n `);
|
||||||
|
await fetchToFile(u, tmp);
|
||||||
|
// 只读前两个字节校验 PE 头,不把整个文件读进内存。
|
||||||
|
const fd = fs.openSync(tmp, 'r');
|
||||||
|
const head = Buffer.alloc(2);
|
||||||
|
fs.readSync(fd, head, 0, 2, 0);
|
||||||
|
fs.closeSync(fd);
|
||||||
|
if (head.toString('latin1') !== 'MZ') throw new Error('下载到的不是 Windows 可执行文件(缺 MZ 头)');
|
||||||
|
fs.renameSync(tmp, BUSYBOX_PATH);
|
||||||
|
console.log('');
|
||||||
|
say(`已安装 ${BUSYBOX_PATH}`);
|
||||||
|
return;
|
||||||
|
} catch (e) {
|
||||||
|
lastErr = e.message;
|
||||||
|
console.log(` 失败:${e.message}`);
|
||||||
|
try { fs.unlinkSync(tmp); } catch (_) { /* 没下载成功就没有临时文件 */ }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
die('busybox-w32 下载失败:' + lastErr,
|
||||||
|
`手动下载 https://frippery.org/files/busybox/busybox.exe 存成 ${BUSYBOX_PATH} 后重跑本脚本;`
|
||||||
|
+ '或先装 Git for Windows(自带 bash,会被自动识别)');
|
||||||
|
}
|
||||||
|
|
||||||
|
async function githubBusyboxUrl() {
|
||||||
|
const r = await fetch('https://api.github.com/repos/rmyorston/busybox-w32/releases/latest', {
|
||||||
|
headers: { 'User-Agent': 'agent-local-launcher' },
|
||||||
|
signal: AbortSignal.timeout(8000),
|
||||||
|
});
|
||||||
|
if (!r.ok) return null;
|
||||||
|
const j = await r.json();
|
||||||
|
const asset = (j.assets || []).find(a => /busybox\.exe$/i.test(a.name));
|
||||||
|
return asset ? asset.browser_download_url : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 带进度地下载(内容长度已知时打百分比;不知道就只打字节数)。
|
||||||
|
async function fetchToFile(url, dest) {
|
||||||
|
const r = await fetch(url, {
|
||||||
|
headers: { 'User-Agent': 'agent-local-launcher' },
|
||||||
|
signal: AbortSignal.timeout(120000),
|
||||||
|
redirect: 'follow',
|
||||||
|
});
|
||||||
|
if (!r.ok) throw new Error(`HTTP ${r.status}`);
|
||||||
|
const total = Number(r.headers.get('content-length') || 0);
|
||||||
|
const out = fs.createWriteStream(dest);
|
||||||
|
let got = 0;
|
||||||
|
for await (const chunk of r.body) {
|
||||||
|
got += chunk.length;
|
||||||
|
if (!out.write(chunk)) await new Promise(res => out.once('drain', res));
|
||||||
|
if (total) process.stdout.write(`\r ${(got / 1024).toFixed(0)}KB / ${(total / 1024).toFixed(0)}KB`);
|
||||||
|
}
|
||||||
|
await new Promise((res, rej) => out.end(err => (err ? rej(err) : res())));
|
||||||
|
if (total && got !== total) throw new Error(`下载不完整(${got}/${total} 字节)`);
|
||||||
|
if (got < 200 * 1024) throw new Error(`文件太小(${got} 字节),大概率不是 busybox`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 3. 工作目录与配置 ----------
|
||||||
|
function ensureWorkspace() {
|
||||||
|
const ws = path.resolve(opt.workspace || path.join(os.homedir(), 'AgentWork'));
|
||||||
|
const dirs = {
|
||||||
|
root: ws,
|
||||||
|
tasks: path.join(ws, 'tasks'),
|
||||||
|
data: path.join(ws, 'data'),
|
||||||
|
skills: path.join(ws, 'skills'),
|
||||||
|
};
|
||||||
|
for (const d of [dirs.tasks, dirs.data, dirs.skills]) fs.mkdirSync(d, { recursive: true });
|
||||||
|
say(`工作目录:${ws}`);
|
||||||
|
return dirs;
|
||||||
|
}
|
||||||
|
|
||||||
|
function ensureConfig(dirs) {
|
||||||
|
if (fs.existsSync(CONFIG_PATH)) {
|
||||||
|
dim(`复用已有配置 ${CONFIG_PATH}(不会覆盖你在网页里改的模型与密钥)`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// YAML 里统一用正斜杠:Node 与 YAML 都不需要转义,反斜杠反而要写两遍。
|
||||||
|
const p = (s) => s.replace(/\\/g, '/');
|
||||||
|
const yml = `# 由 local/start-win.mjs 首次生成,之后不再覆盖。
|
||||||
|
# 字段含义与服务器版一致(见 app/config.example.yml),这里只列本机模式用到的部分。
|
||||||
|
port: ${opt.port}
|
||||||
|
|
||||||
|
# AI 的工作根:文件工具的根就是它,AI 看不到同级的 data/ 与 skills/。
|
||||||
|
workspace_root: "${p(dirs.tasks)}"
|
||||||
|
|
||||||
|
# SQLite(.agent.db)与启动 prompt dump。
|
||||||
|
data_root: "${p(dirs.data)}"
|
||||||
|
|
||||||
|
skills:
|
||||||
|
# 内置技能由启动器首次复制过来,之后只补缺不覆盖;pip 装的依赖落在同级的 deps/。
|
||||||
|
skills_root: "${p(dirs.skills)}"
|
||||||
|
|
||||||
|
# 留空:启动后到设置页添加平台与 API Key,再点「重启」(启动器负责把进程拉起来)。
|
||||||
|
platforms: []
|
||||||
|
|
||||||
|
log_level: info
|
||||||
|
|
||||||
|
# 同栈 MCP(网页搜索 / 图片 / 视频 / 语音)暂未由 Windows 启动器拉起,
|
||||||
|
# 需要时在设置页按卡片添加地址,或先用 local/start.sh 的机器上那份配置。
|
||||||
|
mcp_servers: []
|
||||||
|
`;
|
||||||
|
fs.writeFileSync(CONFIG_PATH, yml, 'utf8');
|
||||||
|
say(`已生成配置 ${CONFIG_PATH}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 4. 技能 ----------
|
||||||
|
// 只补缺不覆盖:用户改过的技能、自己新建的技能都不能被启动器冲掉(与 start.sh 同语义)。
|
||||||
|
function syncSkills(dirs) {
|
||||||
|
const src = path.join(ROOT, 'skills');
|
||||||
|
if (!fs.existsSync(src)) return;
|
||||||
|
let copied = 0;
|
||||||
|
for (const name of fs.readdirSync(src)) {
|
||||||
|
if (name === 'deps' || name.startsWith('.')) continue; // deps 是依赖层,按技能各自安装
|
||||||
|
const from = path.join(src, name);
|
||||||
|
const to = path.join(dirs.skills, name);
|
||||||
|
if (!fs.statSync(from).isDirectory() || fs.existsSync(to)) continue;
|
||||||
|
fs.cpSync(from, to, { recursive: true });
|
||||||
|
copied++;
|
||||||
|
}
|
||||||
|
say(copied ? `补齐技能 ${copied} 个` : '技能已是最新(不覆盖已有目录)');
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 5. 依赖 ----------
|
||||||
|
function ensureDeps() {
|
||||||
|
const appDir = path.join(ROOT, 'app');
|
||||||
|
if (fs.existsSync(path.join(appDir, 'node_modules', 'better-sqlite3'))) return;
|
||||||
|
warn('首次运行需要安装 Node 依赖(app/node_modules 缺失)');
|
||||||
|
const npm = IS_WIN ? 'npm.cmd' : 'npm';
|
||||||
|
const r = spawnSync(npm, ['install'], { cwd: appDir, stdio: 'inherit', shell: IS_WIN });
|
||||||
|
if (r.status !== 0) {
|
||||||
|
die('npm install 失败',
|
||||||
|
'国内网络可先换源:npm config set registry https://registry.npmmirror.com 后重试');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 6. 起 core 并守护 ----------
|
||||||
|
function envFor(shell, dirs) {
|
||||||
|
const deps = path.join(dirs.skills, 'deps');
|
||||||
|
fs.mkdirSync(deps, { recursive: true });
|
||||||
|
return {
|
||||||
|
...process.env,
|
||||||
|
PORT: String(opt.port),
|
||||||
|
HOST: '127.0.0.1', // 本机模式只听回环(与 start.sh 一致)
|
||||||
|
AGENT_CONFIG: CONFIG_PATH,
|
||||||
|
AGENT_FILE_SCOPE: 'workspace', // 文件工具的根放宽到工作目录(本地单用户形态)
|
||||||
|
AGENT_LOCAL_PICK: '1',
|
||||||
|
AGENT_IMAGE_INLINE: '1', // 回环地址厂商拉不到,读图改内联 base64
|
||||||
|
PYTHONPATH: deps,
|
||||||
|
AGENT_SKILLS_DEPS: deps,
|
||||||
|
// 启动器探测到的 shell 直接钉给 core:两边 PATH 可能略有差异,钉住可避免"启动器说
|
||||||
|
// 用 git-bash、core 里却探测成 busybox"这种难查的双份事实。
|
||||||
|
AGENT_SHELL: shell.cmd,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function openBrowser(url) {
|
||||||
|
if (!opt.open) return;
|
||||||
|
try {
|
||||||
|
if (IS_WIN) spawn('cmd', ['/c', 'start', '', url], { stdio: 'ignore', windowsHide: true, detached: true }).unref();
|
||||||
|
else if (process.platform === 'darwin') spawn('open', [url], { stdio: 'ignore', detached: true }).unref();
|
||||||
|
else spawn('xdg-open', [url], { stdio: 'ignore', detached: true }).unref();
|
||||||
|
} catch (_) { /* 打不开浏览器不影响服务 */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
function startCore(shell, dirs) {
|
||||||
|
const env = envFor(shell, dirs);
|
||||||
|
const appDir = path.join(ROOT, 'app');
|
||||||
|
let stopping = false;
|
||||||
|
let restarts = 0;
|
||||||
|
let child = null;
|
||||||
|
|
||||||
|
const launch = () => {
|
||||||
|
child = spawn(process.execPath, ['server/server.js'], { cwd: appDir, env, stdio: 'inherit' });
|
||||||
|
child.on('exit', (code) => {
|
||||||
|
if (stopping) return;
|
||||||
|
restarts++;
|
||||||
|
// 连续崩 5 次就停:多半是配置错(端口被占 / 模型池空),无限重启只会刷屏。
|
||||||
|
if (restarts > 5) die(`core 连续退出 5 次(最后退出码 ${code})`, '看上面的报错;常见原因:端口被占用、config.win.yml 写错');
|
||||||
|
warn(`core 退出了(code=${code}),3 秒后重启(第 ${restarts} 次)`);
|
||||||
|
setTimeout(launch, 3000);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const stop = () => {
|
||||||
|
stopping = true;
|
||||||
|
if (child && child.pid) shellBackend.killTree(child);
|
||||||
|
process.exit(0);
|
||||||
|
};
|
||||||
|
process.on('SIGINT', stop);
|
||||||
|
process.on('SIGTERM', stop);
|
||||||
|
|
||||||
|
launch();
|
||||||
|
const url = `http://127.0.0.1:${opt.port}`;
|
||||||
|
setTimeout(() => openBrowser(url), 1500);
|
||||||
|
say(`启动完成:${url}(Ctrl+C 停止)`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 主流程 ----------
|
||||||
|
(async () => {
|
||||||
|
checkNode();
|
||||||
|
const shell = await ensureShell();
|
||||||
|
const dirs = ensureWorkspace();
|
||||||
|
ensureConfig(dirs);
|
||||||
|
syncSkills(dirs);
|
||||||
|
|
||||||
|
if (opt.check) {
|
||||||
|
say('自检完成(--check 不启动服务)');
|
||||||
|
dim(`配置:${CONFIG_PATH}`);
|
||||||
|
dim(`命令执行环境:${shellBackend.describe({})}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
ensureDeps();
|
||||||
|
startCore(shell, dirs);
|
||||||
|
})();
|
||||||
+20
-12
@@ -257,12 +257,12 @@ CSS
|
|||||||
elif [ -s "$UI_DIR/redirect" ] || [ -s "$UI_DIR/ready" ]; then
|
elif [ -s "$UI_DIR/redirect" ] || [ -s "$UI_DIR/ready" ]; then
|
||||||
url=$(cat "$UI_DIR/redirect" 2>/dev/null)
|
url=$(cat "$UI_DIR/redirect" 2>/dev/null)
|
||||||
[ -n "$url" ] || url=$(cat "$UI_DIR/ready")
|
[ -n "$url" ] || url=$(cat "$UI_DIR/ready")
|
||||||
# 后续启动:会自己跳;首次安装:只停在这页等点击。两种情况都留一个按钮兜底。
|
# auto 模式(写了 redirect)才会自己跳;click 模式就停在这页等点击。
|
||||||
if [ -s "$UI_DIR/redirect" ]; then
|
if [ -s "$UI_DIR/redirect" ]; then
|
||||||
printf '<p class="note">2 秒后自动打开应用;没反应就点下面的按钮。</p>\n'
|
printf '<p class="note">2 秒后自动打开应用;没反应就点下面的按钮。</p>\n'
|
||||||
fi
|
fi
|
||||||
printf '<p class="note"><a class="open" href="%s">打开应用</a> <span class="addr">%s</span></p>\n' "$url" "$url"
|
printf '<p class="note"><a class="open" href="%s">打开应用</a> <span class="addr">%s</span></p>\n' "$url" "$url"
|
||||||
printf '<p class="tip">停止服务:运行 <code>./local/stop.sh</code>(关掉这个页面不影响服务)。</p>\n'
|
printf '<p class="tip">停止服务:运行 <code>./local/stop.sh</code>。</p>\n'
|
||||||
else
|
else
|
||||||
printf '<p class="tip">本页每秒自动刷新,进度会自己出现。</p>\n'
|
printf '<p class="tip">本页每秒自动刷新,进度会自己出现。</p>\n'
|
||||||
fi
|
fi
|
||||||
@@ -319,15 +319,14 @@ ui_stop_ticker() {
|
|||||||
ui_idle() { ui_stop_ticker; rm -f "$UI_DIR/busy"; ui_render; }
|
ui_idle() { ui_stop_ticker; rm -f "$UI_DIR/busy"; ui_render; }
|
||||||
|
|
||||||
ui_done() {
|
ui_done() {
|
||||||
# $1 应用地址 $2 auto|click(首次安装用 click:给链接让用户自己点,不自动跳)
|
# $1 应用地址 $2 auto|click(click = 停在状态页等用户点,不自动跳) $3 note(HTML,可选)
|
||||||
ui_stop_ticker
|
ui_stop_ticker
|
||||||
rm -f "$UI_DIR/busy" "$UI_DIR/error" "$UI_DIR/redirect" "$UI_DIR/ready" "$UI_DIR/note"
|
rm -f "$UI_DIR/busy" "$UI_DIR/error" "$UI_DIR/redirect" "$UI_DIR/ready" "$UI_DIR/note"
|
||||||
printf '%s\n' "${1:-}" > "$UI_DIR/ready"
|
printf '%s\n' "${1:-}" > "$UI_DIR/ready"
|
||||||
if [ "${2:-auto}" = 'auto' ]; then
|
if [ "${2:-auto}" = 'auto' ]; then
|
||||||
printf '%s\n' "${1:-}" > "$UI_DIR/redirect"
|
printf '%s\n' "${1:-}" > "$UI_DIR/redirect"
|
||||||
else
|
elif [ -n "${3:-}" ]; then
|
||||||
# 首次安装用户就停在这页,那下一步怎么配模型也得写在页上,不能只在终端里。
|
printf '%s\n' "$3" > "$UI_DIR/note"
|
||||||
printf '<p class="hint">首次使用:进去后点左下角「用户区」→ 设置 → 模型池,添加平台和 API Key,再点「重启」(服务会自动拉起来)。</p>\n' > "$UI_DIR/note"
|
|
||||||
fi
|
fi
|
||||||
ui_title '已启动'
|
ui_title '已启动'
|
||||||
}
|
}
|
||||||
@@ -795,7 +794,7 @@ kill_tree_hard() {
|
|||||||
do_cleanup() {
|
do_cleanup() {
|
||||||
# 心跳子进程也得收掉,不然退出后它会继续每秒重绘页面。
|
# 心跳子进程也得收掉,不然退出后它会继续每秒重绘页面。
|
||||||
ui_stop_ticker
|
ui_stop_ticker
|
||||||
rm -f "$RUNTIME/ui/busy" "$RUNTIME/supervisor.pid" "$RUNTIME/preview.port"
|
rm -f "$RUNTIME/ui/busy" "$RUNTIME/supervisor.pid" "$RUNTIME/preview.port" "$RUNTIME/tunnel.pid"
|
||||||
for p in $CORE_PID $MCP_PIDS; do kill_tree "$p"; done
|
for p in $CORE_PID $MCP_PIDS; do kill_tree "$p"; done
|
||||||
CORE_PID=''
|
CORE_PID=''
|
||||||
MCP_PIDS=''
|
MCP_PIDS=''
|
||||||
@@ -1104,15 +1103,24 @@ while :; do
|
|||||||
if [ -n "${PREVIEW_PORT:-}" ] && ! port_open "$PREVIEW_PORT"; then
|
if [ -n "${PREVIEW_PORT:-}" ] && ! port_open "$PREVIEW_PORT"; then
|
||||||
warn "预览网关没起来(端口 ${PREVIEW_PORT})——日志:local/.runtime/preview.log"
|
warn "预览网关没起来(端口 ${PREVIEW_PORT})——日志:local/.runtime/preview.log"
|
||||||
fi
|
fi
|
||||||
|
# 隧道 client(可选):配了 tunnel/client.yml 才起,当第 5 个子进程,
|
||||||
|
# 停止时由 do_cleanup 的 kill_tree 一并收掉。它自带指数退避重连、进程不退出,
|
||||||
|
# 所以不需要守护循环;连不上时静默重试,真要查状态就看 local/.runtime/tunnel.log。
|
||||||
|
if [ -f "$ROOT/tunnel/client.yml" ]; then
|
||||||
|
( cd "$ROOT/tunnel" && exec node client.js >>"$RUNTIME/tunnel.log" 2>&1 ) &
|
||||||
|
MCP_PIDS="$MCP_PIDS $!"
|
||||||
|
printf '%s\n' "$!" > "$RUNTIME/tunnel.pid"
|
||||||
|
ui_step '隧道:已启动' ok
|
||||||
|
fi
|
||||||
|
# 一律停在状态页:启动摘要(语音/技能/隧道)和日志尾巴都留在屏幕上,
|
||||||
|
# 用户看完自己点「打开应用」,不会 2 秒就跳走。
|
||||||
if [ "$FIRST_RUN" = 1 ]; then
|
if [ "$FIRST_RUN" = 1 ]; then
|
||||||
# 首次安装:停在状态页,给一个按钮让用户自己点(先看完「首次使用」提示再进去)。
|
ui_done "http://${HOST_ADDR}:${PORT}" click '<p class="hint">首次使用:进去后点左下角「用户区」→ 设置 → 模型池,添加平台和 API Key,再点「重启」(服务会自动拉起来)。</p>'
|
||||||
|
else
|
||||||
ui_done "http://${HOST_ADDR}:${PORT}" click
|
ui_done "http://${HOST_ADDR}:${PORT}" click
|
||||||
|
fi
|
||||||
# 状态页没弹出来时(Linux / AGENT_LOCAL_UI=0)总得给个入口,否则用户什么都看不到。
|
# 状态页没弹出来时(Linux / AGENT_LOCAL_UI=0)总得给个入口,否则用户什么都看不到。
|
||||||
[ "$UI_OPEN" = 1 ] || open_browser
|
[ "$UI_OPEN" = 1 ] || open_browser
|
||||||
else
|
|
||||||
ui_done "http://${HOST_ADDR}:${PORT}" auto
|
|
||||||
open_browser
|
|
||||||
fi
|
|
||||||
printf '\n'
|
printf '\n'
|
||||||
say "已启动:http://$HOST_ADDR:$PORT"
|
say "已启动:http://$HOST_ADDR:$PORT"
|
||||||
sleep 1
|
sleep 1
|
||||||
|
|||||||
@@ -98,6 +98,17 @@ for p in "$PORT" $MCP_PORTS "$pv_port"; do
|
|||||||
done
|
done
|
||||||
done
|
done
|
||||||
|
|
||||||
|
# 5) 隧道 client:它不监听端口,正常随启动器的 do_cleanup 一起收掉;
|
||||||
|
# 启动器被 kill -9 时 EXIT trap 不跑,会漏成孤儿,按它自己写的 pid 文件兜底。
|
||||||
|
if [ -f "$RUNTIME/tunnel.pid" ]; then
|
||||||
|
tpid=$(cat "$RUNTIME/tunnel.pid" 2>/dev/null || printf '')
|
||||||
|
case "$tpid" in ''|*[!0-9]*) tpid='';; esac
|
||||||
|
if [ -n "$tpid" ] && kill -0 "$tpid" 2>/dev/null; then
|
||||||
|
stop_pid "$tpid" '隧道 client'
|
||||||
|
fi
|
||||||
|
rm -f "$RUNTIME/tunnel.pid"
|
||||||
|
fi
|
||||||
|
|
||||||
if [ "$stopped" = 1 ]; then
|
if [ "$stopped" = 1 ]; then
|
||||||
say '已停止'
|
say '已停止'
|
||||||
else
|
else
|
||||||
|
|||||||
+9
-7
@@ -6,7 +6,7 @@
|
|||||||
|---|---|---|---|---|
|
|---|---|---|---|---|
|
||||||
| `web_search/` | `mcp_web_search` | 网页搜索(默认免费 Parallel / Exa,可换成自建 `/search` 上游) | `3000` | `POST /` |
|
| `web_search/` | `mcp_web_search` | 网页搜索(默认免费 Parallel / Exa,可换成自建 `/search` 上游) | `3000` | `POST /` |
|
||||||
| `image_task/` | `mcp_image_task` | 图片生成 / 编辑(文生图走 `/images/generations`,图生图走 `/images/edits`,单工具 op=create/get) | `3000` | `POST /mcp` |
|
| `image_task/` | `mcp_image_task` | 图片生成 / 编辑(文生图走 `/images/generations`,图生图走 `/images/edits`,单工具 op=create/get) | `3000` | `POST /mcp` |
|
||||||
| `video_task/` | `mcp_video_task` | 智谱 CogVideo 视频生成(异步,单工具 op=create/get) | `3000` | `POST /mcp` |
|
| `video_task/` | `mcp_video_task` | 视频生成(任意 OpenAI 兼容 `/videos` 上游,异步,单工具 op=create/get) | `3000` | `POST /mcp` |
|
||||||
| `asr/` | `mcp_asr` | 语音转文字(上游 OpenAI 兼容 `/audio/transcriptions`),**额外带一个给输入框用的 `POST /transcribe`** | `3000` | `POST /mcp` |
|
| `asr/` | `mcp_asr` | 语音转文字(上游 OpenAI 兼容 `/audio/transcriptions`),**额外带一个给输入框用的 `POST /transcribe`** | `3000` | `POST /mcp` |
|
||||||
|
|
||||||
**这些服务一个宿主机端口都不占**——它们只挂在 `agent-mcp-net` 上,由 `agent-core` / `agent-executor`
|
**这些服务一个宿主机端口都不占**——它们只挂在 `agent-mcp-net` 上,由 `agent-core` / `agent-executor`
|
||||||
@@ -50,7 +50,9 @@ mcp_servers:
|
|||||||
> 从旧的「agent + mcp 双仓库」部署升级:先在旧 mcp 仓库目录 `docker compose down`(只需一次,否则同名容器与网络会冲突),再 `up` 本栈。
|
> 从旧的「agent + mcp 双仓库」部署升级:先在旧 mcp 仓库目录 `docker compose down`(只需一次,否则同名容器与网络会冲突),再 `up` 本栈。
|
||||||
|
|
||||||
`image_task` / `video_task` 的 token **不由服务端保存**——每个请求从 `Authorization` header 读取
|
`image_task` / `video_task` 的 token **不由服务端保存**——每个请求从 `Authorization` header 读取
|
||||||
(agent 侧配在 `config.yml` 的 `mcp_servers[].headers`)。`video_task` 用智谱 token;
|
(agent 侧配在 `config.yml` 的 `mcp_servers[].headers`)。`video_task` 走任意 OpenAI 兼容的 videos 上游:
|
||||||
|
提交 `/videos/generations`、查询 `/videos/{task_id}`,地址与模型由 `X-Video-Task-Base-Url` /
|
||||||
|
`X-Video-Task-Model` 指定(两者都必填);
|
||||||
`image_task` 走任意 OpenAI 兼容的 images 上游:文生图 `/images/generations`、图生图 `/images/edits`,
|
`image_task` 走任意 OpenAI 兼容的 images 上游:文生图 `/images/generations`、图生图 `/images/edits`,
|
||||||
上游地址与模型分别由 `X-Image-Task-Base-Url` / `X-Image-Task-Model` 指定(两者都必填)。
|
上游地址与模型分别由 `X-Image-Task-Base-Url` / `X-Image-Task-Model` 指定(两者都必填)。
|
||||||
所以这两个服务不用配任何密钥。
|
所以这两个服务不用配任何密钥。
|
||||||
@@ -71,23 +73,23 @@ mcp_servers:
|
|||||||
本栈默认不给 MCP 服务映射宿主机端口(它们只在 `agent-mcp-net` 内网可达)。要从宿主机直连,
|
本栈默认不给 MCP 服务映射宿主机端口(它们只在 `agent-mcp-net` 内网可达)。要从宿主机直连,
|
||||||
自行在 `docker-compose.yml` 给对应服务加 `ports` 即可。
|
自行在 `docker-compose.yml` 给对应服务加 `ports` 即可。
|
||||||
|
|
||||||
## 图片是怎么到智谱手上的(只有 video_task 关心)
|
## 图片是怎么到上游的(只有 video_task 关心)
|
||||||
|
|
||||||
智谱服务器生成视频前要**自己来拉参考图**,它不带 cookie、不带 `Authorization`。这套链路里**没有任何人上传文件**:
|
上游生成视频前要**自己来拉参考图**,它不带 cookie、不带 `Authorization`。这套链路里**没有任何人上传文件**:
|
||||||
|
|
||||||
```
|
```
|
||||||
AI ──调用 agent 内置的「公开临时 URL」工具(直接传文件路径)──► 拿到一条短命公网 URL
|
AI ──调用 agent 内置的「公开临时 URL」工具(直接传文件路径)──► 拿到一条短命公网 URL
|
||||||
│
|
│
|
||||||
▼
|
▼
|
||||||
AI 把拿到的 URL 当 image_url 交给 video_task:3000/mcp
|
AI 把拿到的 URL 当 image_url 交给 video_task:3000/mcp(转发为上游的 image 字段)
|
||||||
│
|
│
|
||||||
▼
|
▼
|
||||||
智谱 ──匿名 GET──► agent 侧提供的公开临时 URL
|
上游 ──匿名 GET──► agent 侧提供的公开临时 URL
|
||||||
那个文件始终躺在 agent 的任务目录里,零拷贝
|
那个文件始终躺在 agent 的任务目录里,零拷贝
|
||||||
```
|
```
|
||||||
|
|
||||||
- 签发与托管全在 agent 侧(它已集成为一个 tool,AI 直接调用即可,不需要 curl 任何内网入口)。
|
- 签发与托管全在 agent 侧(它已集成为一个 tool,AI 直接调用即可,不需要 curl 任何内网入口)。
|
||||||
- 链接短命:到期或 agent 重启后失效;智谱只在提交任务那一刻拉一次图,完全够用。
|
- 链接短命:到期或 agent 重启后失效;上游只在提交任务那一刻拉一次图,完全够用。
|
||||||
- mcp 这三家一个端口都不露,唯一公网可达的东西只有 agent 自己。
|
- mcp 这三家一个端口都不露,唯一公网可达的东西只有 agent 自己。
|
||||||
|
|
||||||
## 端口与安全
|
## 端口与安全
|
||||||
|
|||||||
@@ -172,7 +172,7 @@ response_format=url
|
|||||||
url: "http://mcp_image_task:3000/mcp"
|
url: "http://mcp_image_task:3000/mcp"
|
||||||
headers:
|
headers:
|
||||||
Authorization: "Bearer <网关 KEY>"
|
Authorization: "Bearer <网关 KEY>"
|
||||||
X-Image-Task-Base-Url: "https://wb.ai.foresh.com/v1"
|
X-Image-Task-Base-Url: "https://your-gateway.example.com/v1"
|
||||||
X-Image-Task-Model: "global:gpt-image-2.5-sunburst"
|
X-Image-Task-Model: "global:gpt-image-2.5-sunburst"
|
||||||
mode: skill
|
mode: skill
|
||||||
```
|
```
|
||||||
@@ -258,7 +258,7 @@ curl -s -X POST http://localhost:8082/mcp \
|
|||||||
-H "Content-Type: application/json" \
|
-H "Content-Type: application/json" \
|
||||||
-H "Accept: application/json, text/event-stream" \
|
-H "Accept: application/json, text/event-stream" \
|
||||||
-H "Authorization: Bearer $TOKEN" \
|
-H "Authorization: Bearer $TOKEN" \
|
||||||
-H "X-Image-Task-Base-Url: https://wb.ai.foresh.com/v1" \
|
-H "X-Image-Task-Base-Url: https://your-gateway.example.com/v1" \
|
||||||
-H "X-Image-Task-Model: global:gpt-image-2.5-sunburst" \
|
-H "X-Image-Task-Model: global:gpt-image-2.5-sunburst" \
|
||||||
-H "Mcp-Session-Id: $SESSION" \
|
-H "Mcp-Session-Id: $SESSION" \
|
||||||
-d '{
|
-d '{
|
||||||
|
|||||||
+101
-228
@@ -1,13 +1,15 @@
|
|||||||
# MCP Video Task
|
# MCP Video Task
|
||||||
|
|
||||||
基于 [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) 的视频生成服务,对接智谱 BigModel 的视频生成**异步**接口,支持**文生视频**和**图生视频**。只有一个工具 `video_task`,用 `op` 区分动作:`op=create` 提交任务、`op=get` 单次查询结果。Server **不内部轮询**——AI 拿到 `task_id` 后自己决定什么时候用 `op="get"` 复查。
|
对接**任意 OpenAI 兼容的视频生成端点**:提交走 `POST {base}/videos/generations`,查询走
|
||||||
|
`GET {base}/videos/{task_id}`。对外只有一个工具 `video_task`,用 `op` 区分动作:
|
||||||
|
|
||||||
- 协议:MCP **Streamable HTTP**(单端点 `/mcp`,支持 SSE 流)
|
- `op=create` 提交任务,立刻回 `task_id`
|
||||||
- 上游:[智谱 BigModel 视频生成(异步)](https://docs.bigmodel.cn/api-reference/模型-api/视频生成异步) + [查询异步结果](https://docs.bigmodel.cn/api-reference/模型-api/查询异步结果)
|
- `op=get` 按 `task_id` 单次查询,**Server 不内部轮询**
|
||||||
- 默认模型:`cogvideox-flash`
|
|
||||||
- 端口:容器内 `3000`(MCP `/mcp` + `/health`,**容器外不映射**,只在 `agent-mcp-net` 内被 agent 访问)
|
- 协议:MCP **Streamable HTTP**(单端点 `/mcp`)
|
||||||
- 鉴权:**无服务端密钥**,每次请求必须从 header 携带智谱 token
|
- 端口:容器内 `3000`(`/mcp` + `/health`)
|
||||||
- 本地文件需要公网 URL 时:不传字节,AI 直接调用 agent 内置的「公开临时 URL」工具拿到短命链接(见下节)
|
- 鉴权:**服务端不存密钥**,每个请求从 header 读
|
||||||
|
- 上游:**不预设任何厂商**,Base-Url / 模型 / 凭据全部由调用方带入
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -22,287 +24,158 @@ cd /root/workspace/tools/agent
|
|||||||
docker compose up -d --build mcp_video_task
|
docker compose up -d --build mcp_video_task
|
||||||
```
|
```
|
||||||
|
|
||||||
服务容器名 `mcp_video_task`,**默认不占宿主机端口**:由 agent 走 `agent-mcp-net` 按容器名访问
|
容器名 `mcp_video_task`,不占宿主机端口,由 agent 走 `agent-mcp-net` 按容器名访问。
|
||||||
(`http://mcp_video_task:3000/mcp`)。要从宿主机 curl 调试,自行给该服务加 `ports` 映射。
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 容器内健康检查(无需占端口)
|
# 容器内健康检查
|
||||||
docker exec mcp_video_task node -e "fetch('http://localhost:3000/health').then(r=>r.text()).then(console.log)"
|
docker exec mcp_video_task node -e "fetch('http://localhost:3000/health').then(r=>r.text()).then(console.log)"
|
||||||
# {"status":"ok","service":"video_task","sessions":0}
|
# {"status":"ok","service":"video_task","sessions":0}
|
||||||
```
|
```
|
||||||
|
|
||||||
> 下文 curl 示例里的 `localhost:8083` 均指“临时打开了调试端口”的情形。
|
|
||||||
|
|
||||||
### MCP 客户端配置
|
### MCP 客户端配置
|
||||||
|
|
||||||
#### Claude Desktop / Cursor 等支持 `headers` 配置的客户端
|
|
||||||
|
|
||||||
```jsonc
|
```jsonc
|
||||||
// Claude Desktop: ~/Library/Application Support/Claude/claude_desktop_config.json
|
|
||||||
// Cursor: ~/.cursor/mcp.json
|
|
||||||
{
|
{
|
||||||
"mcpServers": {
|
"mcpServers": {
|
||||||
"video_task": {
|
"video_task": {
|
||||||
"url": "http://localhost:8083/mcp",
|
"type": "http",
|
||||||
|
"url": "http://mcp_video_task:3000/mcp",
|
||||||
"headers": {
|
"headers": {
|
||||||
"Authorization": "Bearer <your-zhipu-api-key>"
|
"Authorization": "Bearer <上游 API Key>",
|
||||||
|
"X-Video-Task-Base-Url": "https://<host>/v1",
|
||||||
|
"X-Video-Task-Model": "<上游模型 id>"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
> 上面的 `localhost:8083` 只是示例:本栈默认不给 MCP 服务映射宿主端口,要直连需自行加 `ports`。
|
---
|
||||||
|
|
||||||
> **重要**:客户端必须在 **每一个 HTTP 请求**(`initialize` / `notifications/initialized` / `tools/call`)都带上 `Authorization` header。
|
## 三个 header
|
||||||
|
|
||||||
|
| header | 必填 | 说明 |
|
||||||
|
|---|---|---|
|
||||||
|
| `Authorization` | 是 | `Bearer <token>`,原样转给上游 |
|
||||||
|
| `X-Video-Task-Base-Url` | 是 | 完整 http(s) 地址,填到 `/v1` 即可;直接填到 `/videos/generations` 或 `/videos` 也会被剥回 base |
|
||||||
|
| `X-Video-Task-Model` | 是 | 上游模型 id,原样透传;不猜缺省值 |
|
||||||
|
|
||||||
|
配置缺失或非法时,工具直接回 `isError` 并说明缺哪个 header,不会去打上游。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 工具:video_task
|
## 工具:video_task
|
||||||
|
|
||||||
单个工具,`op` 必填,只有两个取值:
|
|
||||||
|
|
||||||
| op | 作用 | 同步/异步 |
|
|
||||||
|---|---|---|
|
|
||||||
| `create` | 提交一个视频生成任务,立刻返回 `task_id` | 同步(仅提交) |
|
|
||||||
| `get` | 用 `task_id` 拉一次当前结果 | 同步(单次查询,不轮询) |
|
|
||||||
|
|
||||||
### 参数(AI 可见)
|
### 参数(AI 可见)
|
||||||
|
|
||||||
| 名称 | 类型 | 必填 | 说明 |
|
| 参数 | 类型 | 说明 |
|
||||||
|---|---|---|---|
|
|---|---|---|
|
||||||
| `op` | `"create"` \| `"get"` | ✅ | 要执行的操作 |
|
| `op` | `create` \| `get` | 必填 |
|
||||||
| `prompt` | string | op=create 时与 `image_url` 二选一 | 视频文本描述,最大 512 字符;与 `image_url` 同传时作为运动/动作描述 |
|
| `prompt` | string | 视频描述,`create` 时与 `image_url` 至少给一个 |
|
||||||
| `image_url` | string (URL) | ❌ | 参考图 URL(**单张**,不支持数组 / 多张 / 首尾帧)。图片 ≤ 5MB,格式 png/jpeg/jpg。本地文件请先用 agent 内置的公开临时 URL 工具换成公网链接(上一节) |
|
| `image_url` | string | 参考图(图生视频),公开可访问的 png/jpeg URL |
|
||||||
| `with_audio` | boolean | ❌ | 是否生成 AI 音效,默认 `false`(仅 op=create 使用) |
|
| `seconds` | int | 时长(秒),留空用上游默认 |
|
||||||
| `task_id` | string | op=get 时必填 | `op=create` 返回的 `id` |
|
| `aspect_ratio` | string | 画幅,如 `16:9` / `9:16` / `1:1` |
|
||||||
|
| `resolution` | string | 分辨率,如 `768P` / `1080P` |
|
||||||
### 服务端 Header 覆盖项(AI 看不到)
|
| `negative_prompt` | string | 不希望出现的画面 |
|
||||||
|
| `enable_audio` | bool | 是否生成音频,默认 false(旧名 `with_audio` 同样接受) |
|
||||||
| Header | 类型 | 默认 | 说明 |
|
| `task_id` | string | `create` 返回的 id,`get` 时必填 |
|
||||||
|---|---|---|---|
|
|
||||||
| `X-Video-Task-Model` / `X-Mcp-Model` / `X-Model` | string | `cogvideox-flash` | 覆盖模型 |
|
|
||||||
| `X-Video-Task-Quality` | string | `speed` | `speed`(速度优先)或 `quality`(质量优先) |
|
|
||||||
| `X-Video-Task-Fps` | int | `30` | `30` 或 `60` |
|
|
||||||
| `X-Video-Task-Watermark` | bool | `true` | 是否添加 AI 水印;关闭需先在智谱后台签署免责声明 |
|
|
||||||
|
|
||||||
模型名串识别顺序(首个非空值生效):`X-Video-Task-Model` → `X-Mcp-Model` → `X-Model` → 默认。
|
|
||||||
|
|
||||||
### 返回(op=create)
|
### 返回(op=create)
|
||||||
|
|
||||||
立刻返回智谱提交结果:
|
|
||||||
|
|
||||||
```jsonc
|
|
||||||
{
|
|
||||||
"content": [
|
|
||||||
{ "type": "text", "text": "Model: cogvideox-flash\ntask_id: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\nrequest_id: yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy\ntask_status: PROCESSING\n\nVideo generation is asynchronous. Call this tool again with op=\"get\" and task_id=\"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\" to fetch the result." }
|
|
||||||
]
|
|
||||||
}
|
|
||||||
```
|
```
|
||||||
|
task_id: <id>
|
||||||
|
model: <上游模型 id>
|
||||||
|
status: queued
|
||||||
|
|
||||||
`task_status` 通常为 `PROCESSING`,极少数情况下可能直接 `SUCCESS`(极快完成的短任务)。
|
Video generation is asynchronous. Call this tool again with op="get" and task_id="<id>" to fetch the result.
|
||||||
|
```
|
||||||
|
|
||||||
### 返回(op=get)
|
### 返回(op=get)
|
||||||
|
|
||||||
- **`SUCCESS`**:单个 `text` 块,含 `Video URL`(智谱签名 URL,**24h 左右有效**,需及时转存),以及 `Cover` 封面图:
|
任务完成:
|
||||||
```jsonc
|
|
||||||
{
|
```
|
||||||
"content": [
|
task_id: <id>
|
||||||
{ "type": "text", "text": "task_id: ...\nmodel: cogvideox-flash\ntask_status: SUCCESS\nVideo URL: https://...\nCover: https://..." }
|
model: <上游模型 id>
|
||||||
]
|
status: completed
|
||||||
}
|
Video URL: https://...
|
||||||
```
|
credit: 62.29
|
||||||
- **`PROCESSING`**:`isError: false`,正文给出当前状态,建议稍候再查。
|
note: <上游附带的提示,如直链有效期>
|
||||||
- **`FAIL`**:`isError: true`,正文含 `task_status` 和智谱返回的 `error` 详情。
|
```
|
||||||
|
|
||||||
|
未完成 / 失败:回 `status` 与 `progress`,失败时附上游 `error` 原文,并置 `isError=true`。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 上游要求
|
||||||
|
|
||||||
|
只要满足这两条,任何实现都能接(自建网关、云厂商、本地服务):
|
||||||
|
|
||||||
|
1. `POST {base}/videos/generations` 返回 `task_id` 或 `id`
|
||||||
|
2. `GET {base}/videos/{task_id}` 返回 `status`;完成时带 `videos[].url` 或 `data[].url`
|
||||||
|
|
||||||
|
`status` 按小写比较:`completed` / `succeeded` / `success` 视为完成,`failed` / `error` /
|
||||||
|
`cancelled` 视为失败,其余按进行中处理。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 本地文件 → 公网 URL(本服务不搬字节)
|
## 本地文件 → 公网 URL(本服务不搬字节)
|
||||||
|
|
||||||
`image_url` 必须是一个**公网可达**的 URL(智谱服务器会自己去拉)。图片在本地盘上时,本服务不负责上传:
|
图生视频要的是**公网可访问的 URL**,不是字节流。本地文件这样走:
|
||||||
agent 侧已集成为一个 **tool**,AI 直接传文件路径就能拿到一条公开临时 URL,拿来填 `image_url` 即可,
|
|
||||||
不需要 curl 任何地址、不需要任何配置。
|
|
||||||
|
|
||||||
- 文件始终躺在 agent 的任务目录里,零拷贝;链接短命、到期或 agent 重启后失效。
|
|
||||||
- 智谱只在提交任务那一刻拉一次图,短命链接完全够用。
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 鉴权细节
|
|
||||||
|
|
||||||
每个 HTTP 请求必须携带智谱 API Token,server 从以下 header 字段按顺序识别,**首个非空值生效**:
|
|
||||||
|
|
||||||
| 优先级 | Header | 说明 |
|
|
||||||
|---|---|---|
|
|
||||||
| 1 | `X-Video-Task-Token: <token>` | 直传,避免与客户端自身的 Authorization 冲突 |
|
|
||||||
| 2 | `X-Mcp-Token: <token>` | 通用兜底 |
|
|
||||||
| 3 | `Authorization: Bearer <token>` | 标准 OAuth 风格(排最后是为避免误用) |
|
|
||||||
|
|
||||||
Token 仅在每次 tool call 时从 header 读取,不写入任何存储、不进 session。
|
|
||||||
|
|
||||||
### 错误响应
|
|
||||||
|
|
||||||
| 场景 | HTTP 状态 | 表现 |
|
|
||||||
|---|---|---|
|
|
||||||
| initialize 时缺 token | `401` | JSON-RPC `error.message` 提示补充 header |
|
|
||||||
| 智谱 API 4xx/5xx | `200`(MCP 工具返回) | `isError: true`,正文含智谱返回的状态码和 body |
|
|
||||||
| 网络失败 | `200`(MCP 工具返回) | `isError: true`,正文含 `fetch` 错误信息 |
|
|
||||||
| 上游挂住不回(超时 >30s) | `200`(MCP 工具返回) | `isError: true`,正文提示 timed out;`fetch` 带 `AbortSignal.timeout`,不会无限卡住工具调用 |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 推荐用法(AI 视角)
|
|
||||||
|
|
||||||
```
|
```
|
||||||
1. 如果手头是【本地文件】:先调用 agent 内置的「公开临时 URL」工具拿到一条公网链接(上一节),再进第 2 步
|
AI ──调用 agent 内置的「公开临时 URL」工具(直接传文件路径)──► 拿到一条短命公网 URL
|
||||||
2. 调用 video_task({ op: "create", prompt, image_url?, with_audio? })
|
│
|
||||||
3. 拿到 task_id → 等待若干秒(建议 2~5 秒)
|
▼
|
||||||
4. 调用 video_task({ op: "get", task_id })
|
AI 把 URL 当 image_url 交给 video_task:3000/mcp(转成上游的 image 字段)
|
||||||
- 若 PROCESSING → 等一会再调
|
│
|
||||||
- 若 SUCCESS → 拿到 video URL,贴给用户 / 下载 / 二次编辑
|
▼
|
||||||
- 若 FAIL → 展示错误信息,结束
|
上游 ──匿名 GET──► agent 侧提供的公开临时 URL(文件始终躺在任务目录里,零拷贝)
|
||||||
```
|
```
|
||||||
|
|
||||||
> `image_url` 必须是公网可达 URL;本地文件走 agent 内置工具,本服务不参与上传。
|
链接短命:到期或 agent 重启后失效;上游只在提交任务那一刻拉一次图,够用。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 用 curl 手工调试
|
## 用 curl 手工调试
|
||||||
|
|
||||||
MCP Streamable HTTP 不是普通 REST,**必须按顺序**:`initialize` → `notifications/initialized` → `tools/call`。下面用一行版串起来:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 把 <your-zhipu-api-key> 替换成你智谱的 API Key
|
URL=http://127.0.0.1:3000/mcp # 容器内;宿主机调试需自行映射端口
|
||||||
TOKEN="<your-zhipu-api-key>"
|
H=(-H 'Content-Type: application/json' -H 'Accept: application/json, text/event-stream'
|
||||||
|
-H 'Authorization: Bearer <token>'
|
||||||
|
-H 'X-Video-Task-Base-Url: https://<host>/v1'
|
||||||
|
-H 'X-Video-Task-Model: <model>')
|
||||||
|
|
||||||
# 1. initialize 拿 sessionId
|
# 1. initialize,从响应头取 mcp-session-id
|
||||||
SESSION=$(curl -s -D - -X POST http://localhost:8083/mcp \
|
curl -s -D - "${H[@]}" -X POST $URL \
|
||||||
-H "Content-Type: application/json" \
|
-d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"c","version":"0"}}}'
|
||||||
-H "Accept: application/json, text/event-stream" \
|
|
||||||
-H "Authorization: Bearer $TOKEN" \
|
|
||||||
-d '{
|
|
||||||
"jsonrpc": "2.0",
|
|
||||||
"id": 1,
|
|
||||||
"method": "initialize",
|
|
||||||
"params": {
|
|
||||||
"protocolVersion": "2024-11-05",
|
|
||||||
"capabilities": {},
|
|
||||||
"clientInfo": { "name": "curl", "version": "1.0" }
|
|
||||||
}
|
|
||||||
}' | grep -i '^mcp-session-id:' | awk '{print $2}' | tr -d '\r\n')
|
|
||||||
|
|
||||||
echo "Session: $SESSION"
|
# 2. 提交任务
|
||||||
|
curl -s "${H[@]}" -H 'mcp-session-id: <sid>' -X POST $URL \
|
||||||
|
-d '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"video_task","arguments":{"op":"create","prompt":"一只猫在草地上跑"}}}'
|
||||||
|
|
||||||
# 2. notifications/initialized
|
# 3. 查结果
|
||||||
curl -s -X POST http://localhost:8083/mcp \
|
curl -s "${H[@]}" -H 'mcp-session-id: <sid>' -X POST $URL \
|
||||||
-H "Content-Type: application/json" \
|
-d '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"video_task","arguments":{"op":"get","task_id":"<id>"}}}'
|
||||||
-H "Accept: application/json, text/event-stream" \
|
|
||||||
-H "Authorization: Bearer $TOKEN" \
|
|
||||||
-H "Mcp-Session-Id: $SESSION" \
|
|
||||||
-d '{"jsonrpc": "2.0", "method": "notifications/initialized"}'
|
|
||||||
|
|
||||||
# 3. 列出工具(可选验证)
|
|
||||||
curl -s -X POST http://localhost:8083/mcp \
|
|
||||||
-H "Content-Type: application/json" \
|
|
||||||
-H "Accept: application/json, text/event-stream" \
|
|
||||||
-H "Authorization: Bearer $TOKEN" \
|
|
||||||
-H "Mcp-Session-Id: $SESSION" \
|
|
||||||
-d '{"jsonrpc": "2.0", "id": 2, "method": "tools/list"}'
|
|
||||||
|
|
||||||
# 4. 提交文生视频任务(op=create)
|
|
||||||
curl -s -X POST http://localhost:8083/mcp \
|
|
||||||
-H "Content-Type: application/json" \
|
|
||||||
-H "Accept: application/json, text/event-stream" \
|
|
||||||
-H "Authorization: Bearer $TOKEN" \
|
|
||||||
-H "Mcp-Session-Id: $SESSION" \
|
|
||||||
-d '{
|
|
||||||
"jsonrpc": "2.0",
|
|
||||||
"id": 3,
|
|
||||||
"method": "tools/call",
|
|
||||||
"params": {
|
|
||||||
"name": "video_task",
|
|
||||||
"arguments": {
|
|
||||||
"op": "create",
|
|
||||||
"prompt": "A cat is playing with a ball.",
|
|
||||||
"with_audio": true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}'
|
|
||||||
|
|
||||||
# 5. 查结果(op=get,替换下面的 <task_id>)
|
|
||||||
curl -s -X POST http://localhost:8083/mcp \
|
|
||||||
-H "Content-Type: application/json" \
|
|
||||||
-H "Accept: application/json, text/event-stream" \
|
|
||||||
-H "Authorization: Bearer $TOKEN" \
|
|
||||||
-H "Mcp-Session-Id: $SESSION" \
|
|
||||||
-d '{
|
|
||||||
"jsonrpc": "2.0",
|
|
||||||
"id": 4,
|
|
||||||
"method": "tools/call",
|
|
||||||
"params": {
|
|
||||||
"name": "video_task",
|
|
||||||
"arguments": { "op": "get", "task_id": "<task_id>" }
|
|
||||||
}
|
|
||||||
}'
|
|
||||||
```
|
```
|
||||||
|
|
||||||
响应是 SSE 格式(`event: message` + `data: {...}`),用 `grep '^data:'` 抽 JSON 即可。
|
响应是 SSE(`event: message` + `data: {...}`),取 `data:` 那行解析。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## 架构与文件
|
## 架构与文件
|
||||||
|
|
||||||
```
|
```
|
||||||
video_task/
|
mcp/video_task/
|
||||||
├── Dockerfile # node:22-slim,安装依赖后启动 MCP HTTP server
|
├── Dockerfile
|
||||||
├── .dockerignore # 排除 node_modules
|
├── package.json
|
||||||
package.json # @modelcontextprotocol/sdk + express
|
├── README.md
|
||||||
├── README.md # 本文件
|
└── src/mcp-server.js # 全部逻辑:header 解析 / 上游调用 / MCP 服务
|
||||||
└── src/
|
|
||||||
└── mcp-server.js # 单文件实现:HTTP server + MCP transport + 单工具(op 分发)
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### 关键设计
|
### 关键设计
|
||||||
|
|
||||||
- **单工具 + `op` 分发**:`video_task(op=create|get)` 替代原来的 `video_gen` + `query_video` 双工具,AI 面对的工具面更小,参数按 op 在 handler 侧校验
|
- **无状态**:不存密钥、不存任务,重启即忘。任务状态由上游持有,`task_id` 就是全部上下文。
|
||||||
- **每 session 一个 transport + server**:通过 `Mcp-Session-Id` 复用,避免每请求重建
|
- **不轮询**:`op=get` 只拉一次。轮询节奏由 AI 决定,避免服务端挂着长任务占资源。
|
||||||
- **Token 闭包注入**:在 Express 入口处从 header 提取 token,闭包传给 tool 回调;不依赖 SDK 内部字段
|
- **配置错误不打上游**:缺 header 时同步返回 `isError`,省一次无意义的 400。
|
||||||
- **AI 可见 vs AI 不可见**:
|
- **`wait=false` 提交**:立刻拿 `task_id`,不让工具调用被上游排队拖死。
|
||||||
- AI 只看到 `op / prompt / image_url / with_audio / task_id`
|
|
||||||
- `model / quality / fps / watermark_enabled` 全部由 HTTP header 注入,避免 AI 误传或被诱导调高价档
|
|
||||||
- **异步语义暴露给 AI**:服务端不做轮询,`op=create` 只提交、`op=get` 只查一次。AI 自主决定节奏
|
|
||||||
- **服务端自动 `request_id`**:每次提交服务端生成一个 UUID 作为智谱 `request_id`,便于日志关联,但不暴露给 AI
|
|
||||||
- **不搬字节**:本地文件 -> 公网 URL 完全由 agent 侧集成的「公开临时 URL」工具完成,本服务不参与;所以本体不加任何写入口、不落盘、不需要额外端口
|
|
||||||
- **链接短命**:公开临时 URL 到期或 agent 重启后失效;智谱只需在提交任务那一刻拉一次图
|
|
||||||
|
|
||||||
### 默认模型
|
|
||||||
|
|
||||||
```js
|
|
||||||
// src/mcp-server.js
|
|
||||||
const DEFAULT_MODEL = "cogvideox-flash";
|
|
||||||
```
|
|
||||||
|
|
||||||
修改后 `docker compose up -d --build mcp_video_task` 即可生效。
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 常见问题
|
|
||||||
|
|
||||||
**Q: AI 拿到 task_id 后立刻 op=get 一直 PROCESSING,怎么办?**
|
|
||||||
A: AI 自己 sleep 几秒再调(建议 2~5 秒间隔)。这是设计取舍:把节奏控制权交给 AI 模型,而不是服务端硬编码超时。
|
|
||||||
|
|
||||||
**Q: 视频 URL 多久过期?**
|
|
||||||
A: 智谱签发 URL 默认 24h 左右。需要在收到后及时转存到自己的 OSS/S3。
|
|
||||||
|
|
||||||
**Q: 为什么 quality / fps 不让 AI 直接传?**
|
|
||||||
A: 这些是技术档位,与成本/单价挂钩。让 AI 自主挑 `quality=quality + fps=60` 会爆账号预算。改成 header 由部署方注入更可控。
|
|
||||||
|
|
||||||
**Q: 报错 `Missing valid Mcp-Session-Id`?**
|
|
||||||
A: 漏发了 `Mcp-Session-Id` header,或调 `tools/call` 前没先 `initialize`。
|
|
||||||
|
|
||||||
**Q: 同一 task_id 能并发查吗?**
|
|
||||||
A: 可以。`/async-result/{id}` 是幂等的读接口,并发无副作用。
|
|
||||||
|
|
||||||
**Q: 换模型需要重连 MCP session 吗?**
|
|
||||||
A: 不需要。Model header 在每次 `tools/call` 都从当前请求读取。
|
|
||||||
|
|
||||||
**Q: 上传的图片多久过期?**
|
|
||||||
A: 本服务不存图,不存在“上传的图片”:要用的图在 agent 的任务目录里,AI 用 agent 内置的公开临时 URL 工具现取一条短命链接给智谱拉。链接过期或 agent 重启后该 URL 失效,但智谱只在提交任务时拉一次,不受影响。
|
|
||||||
|
|||||||
+164
-246
@@ -6,26 +6,16 @@ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/
|
|||||||
import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
|
import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
|
|
||||||
const ZHIPU_SUBMIT_URL =
|
// 上游必须是 OpenAI 兼容的视频端点:提交 POST /videos/generations,查询 GET /videos/{task_id}。
|
||||||
"https://open.bigmodel.cn/api/paas/v4/videos/generations";
|
// Base-Url / 模型 / 凭据全部由调用方随每个请求用 header 带入(X-Video-Task-Base-Url /
|
||||||
const ZHIPU_QUERY_URL = (id) =>
|
// X-Video-Task-Model / Authorization),服务自己不存、也不预设任何厂商。
|
||||||
`https://open.bigmodel.cn/api/paas/v4/async-result/${encodeURIComponent(id)}`;
|
|
||||||
|
|
||||||
// 默认模型:cogvideox-flash
|
// 提交与查询都是快接口(wait=false 立刻回 task_id),卡住基本等于上游挂了。
|
||||||
const DEFAULT_MODEL = "cogvideox-flash";
|
const UPSTREAM_TIMEOUT_MS = 60_000;
|
||||||
|
|
||||||
// AI 不可见的服务端默认(可被同名 header 覆盖)
|
|
||||||
const DEFAULT_QUALITY = "speed"; // speed | quality
|
|
||||||
const DEFAULT_FPS = 30; // 30 | 60
|
|
||||||
const DEFAULT_WATERMARK_ENABLED = true; // 平台政策默认 true
|
|
||||||
|
|
||||||
// submit/query 都是快接口,卡住基本等于上游挂了;限时避免工具调用被拖死
|
|
||||||
const UPSTREAM_TIMEOUT_MS = 30_000;
|
|
||||||
|
|
||||||
// ── 优雅退出 ──────────────────────────────────────────────────────────────
|
// ── 优雅退出 ──────────────────────────────────────────────────────────────
|
||||||
// 容器里 node 以 PID 1 运行且未注册 SIGTERM 处理器时,内核不会对其执行默认
|
// 容器里 node 以 PID 1 运行且未注册 SIGTERM 处理器时,内核不会对其执行默认
|
||||||
// 终止动作,docker stop/restart 会白等满 10s 宽限期才被 SIGKILL。
|
// 终止动作,docker stop/restart 会白等满 10s 宽限期才被 SIGKILL。
|
||||||
// 显式注册处理器,关闭 MCP session 与长连接后立即退出;3s 定时器为兜底。
|
|
||||||
let httpServer = null;
|
let httpServer = null;
|
||||||
let closeAllSessions = () => {};
|
let closeAllSessions = () => {};
|
||||||
let shuttingDown = false;
|
let shuttingDown = false;
|
||||||
@@ -43,11 +33,7 @@ process.on("SIGTERM", () => shutdown("SIGTERM"));
|
|||||||
process.on("SIGINT", () => shutdown("SIGINT"));
|
process.on("SIGINT", () => shutdown("SIGINT"));
|
||||||
|
|
||||||
function parseArgs(argv) {
|
function parseArgs(argv) {
|
||||||
const args = {
|
const args = { http: false, port: 3000, host: "0.0.0.0" };
|
||||||
http: false,
|
|
||||||
port: 3000,
|
|
||||||
host: "0.0.0.0",
|
|
||||||
};
|
|
||||||
for (let i = 0; i < argv.length; i++) {
|
for (let i = 0; i < argv.length; i++) {
|
||||||
const a = argv[i];
|
const a = argv[i];
|
||||||
if (a === "--http") args.http = true;
|
if (a === "--http") args.http = true;
|
||||||
@@ -57,74 +43,84 @@ function parseArgs(argv) {
|
|||||||
return args;
|
return args;
|
||||||
}
|
}
|
||||||
|
|
||||||
function pickToken(headers) {
|
// 对外只有三个 header:Authorization / X-Video-Task-Base-Url / X-Video-Task-Model。
|
||||||
|
function pickAuthToken(headers) {
|
||||||
if (!headers) return null;
|
if (!headers) return null;
|
||||||
const candidates = [
|
const s = String(headers["authorization"] || "").trim();
|
||||||
headers["x-video-task-token"],
|
if (!s) return null;
|
||||||
headers["x-mcp-token"],
|
|
||||||
headers["authorization"],
|
|
||||||
];
|
|
||||||
for (const v of candidates) {
|
|
||||||
if (!v) continue;
|
|
||||||
const s = String(v).trim();
|
|
||||||
if (!s) continue;
|
|
||||||
if (/^Bearer\s+/i.test(s)) {
|
if (/^Bearer\s+/i.test(s)) {
|
||||||
const t = s.replace(/^Bearer\s+/i, "").trim();
|
const t = s.replace(/^Bearer\s+/i, "").trim();
|
||||||
if (t) return t;
|
return t || null;
|
||||||
} else {
|
}
|
||||||
return s;
|
return s;
|
||||||
}
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function pickModel(headers) {
|
function pickHeaderString(headers, name) {
|
||||||
if (!headers) return null;
|
if (!headers) return null;
|
||||||
const v =
|
const v = headers[name];
|
||||||
headers["x-video-task-model"] ||
|
if (v === undefined || v === null) return null;
|
||||||
headers["x-mcp-model"] ||
|
|
||||||
headers["x-model"];
|
|
||||||
if (!v) return null;
|
|
||||||
const s = String(v).trim();
|
const s = String(v).trim();
|
||||||
return s || null;
|
return s || null;
|
||||||
}
|
}
|
||||||
|
|
||||||
function pickHeaderString(headers, name, fallback) {
|
function pickBaseUrl(headers) {
|
||||||
if (!headers) return fallback;
|
return pickHeaderString(headers, "x-video-task-base-url");
|
||||||
const v = headers[name];
|
|
||||||
if (v === undefined || v === null) return fallback;
|
|
||||||
const s = String(v).trim();
|
|
||||||
return s ? s : fallback;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function pickHeaderInt(headers, name, fallback) {
|
function pickModel(headers) {
|
||||||
if (!headers) return fallback;
|
return pickHeaderString(headers, "x-video-task-model");
|
||||||
const v = headers[name];
|
|
||||||
if (v === undefined || v === null) return fallback;
|
|
||||||
const n = parseInt(String(v).trim(), 10);
|
|
||||||
return Number.isFinite(n) ? n : fallback;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function pickHeaderBool(headers, name, fallback) {
|
// 解析 Base-Url:必须是完整 http(s) URL。允许调用方直接填到 /videos/generations
|
||||||
if (!headers) return fallback;
|
// 或 /videos(照抄文档的写法),统一剥回 base——否则查询会被拼成两条路径。
|
||||||
const v = headers[name];
|
function resolveBaseUrl(rawBase) {
|
||||||
if (v === undefined || v === null) return fallback;
|
const base = String(rawBase || "").trim().replace(/\/+$/, "");
|
||||||
const s = String(v).trim().toLowerCase();
|
if (!base) {
|
||||||
if (s === "true" || s === "1" || s === "yes") return true;
|
throw new Error(
|
||||||
if (s === "false" || s === "0" || s === "no") return false;
|
"Missing X-Video-Task-Base-Url: pass the upstream base URL (e.g. https://<host>/v1)."
|
||||||
return fallback;
|
);
|
||||||
|
}
|
||||||
|
if (!/^https?:\/\//i.test(base)) {
|
||||||
|
throw new Error(
|
||||||
|
`Invalid X-Video-Task-Base-Url "${base}": must be a full http(s) URL.`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return base.replace(/\/videos(\/generations)?$/i, "");
|
||||||
}
|
}
|
||||||
|
|
||||||
async function callZhipu({ url, token, method = "POST", body }) {
|
// 模型只由 header 决定,AI 看不到也填不了。不猜缺省值:猜错只会换来含义不明的 400。
|
||||||
|
function resolveModel(headers) {
|
||||||
|
const model = pickModel(headers);
|
||||||
|
if (!model) {
|
||||||
|
throw new Error("Missing X-Video-Task-Model: pass the upstream model name.");
|
||||||
|
}
|
||||||
|
return model;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 一次解析出本次请求的上游、凭据、模型。配置问题同步抛错,直接回给调用方。
|
||||||
|
function resolveTarget(headers) {
|
||||||
|
const token = pickAuthToken(headers);
|
||||||
|
if (!token) {
|
||||||
|
throw new Error('Missing Authorization: use "Authorization: Bearer <token>".');
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
base: resolveBaseUrl(pickBaseUrl(headers)),
|
||||||
|
token,
|
||||||
|
model: resolveModel(headers),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// 统一的上游请求:超时、错误体解析都在这层,提交与查询共用。
|
||||||
|
async function callUpstream({ url, token, method = "POST", body }) {
|
||||||
const init = {
|
const init = {
|
||||||
method,
|
method,
|
||||||
headers: {
|
headers: { Authorization: `Bearer ${token}` },
|
||||||
Authorization: `Bearer ${token}`,
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
},
|
|
||||||
signal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS),
|
signal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS),
|
||||||
};
|
};
|
||||||
if (body !== undefined) init.body = JSON.stringify(body);
|
if (body !== undefined) {
|
||||||
|
init.headers["Content-Type"] = "application/json";
|
||||||
|
init.body = JSON.stringify(body);
|
||||||
|
}
|
||||||
let resp;
|
let resp;
|
||||||
try {
|
try {
|
||||||
resp = await fetch(url, init);
|
resp = await fetch(url, init);
|
||||||
@@ -143,9 +139,7 @@ async function callZhipu({ url, token, method = "POST", body }) {
|
|||||||
data = { raw: text };
|
data = { raw: text };
|
||||||
}
|
}
|
||||||
if (!resp.ok) {
|
if (!resp.ok) {
|
||||||
const err = new Error(
|
const err = new Error(`Upstream error: ${resp.status} ${resp.statusText} - ${text}`);
|
||||||
`Zhipu API error: ${resp.status} ${resp.statusText} - ${text}`
|
|
||||||
);
|
|
||||||
err.status = resp.status;
|
err.status = resp.status;
|
||||||
err.detail = data;
|
err.detail = data;
|
||||||
throw err;
|
throw err;
|
||||||
@@ -153,96 +147,74 @@ async function callZhipu({ url, token, method = "POST", body }) {
|
|||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ===== op=create:提交视频生成(同步只提交,立刻返回)=====
|
// ===== op=create:提交视频生成(wait=false,立刻返回 task_id)=====
|
||||||
async function submitVideo({
|
async function submitVideo({ base, token, model, prompt, image_url, seconds, aspect_ratio, resolution, negative_prompt, enable_audio }) {
|
||||||
token,
|
const body = { model, wait: false };
|
||||||
model,
|
|
||||||
prompt,
|
|
||||||
image_url,
|
|
||||||
quality,
|
|
||||||
with_audio,
|
|
||||||
fps,
|
|
||||||
watermark_enabled,
|
|
||||||
}) {
|
|
||||||
// 平台要求 image_url 和 prompt 至少传一个(handler 侧已校验)
|
|
||||||
const body = {
|
|
||||||
model,
|
|
||||||
quality,
|
|
||||||
with_audio: Boolean(with_audio),
|
|
||||||
watermark_enabled: Boolean(watermark_enabled),
|
|
||||||
fps,
|
|
||||||
// 由服务端生成唯一 request_id,便于日志关联;不暴露给 AI
|
|
||||||
request_id: randomUUID(),
|
|
||||||
};
|
|
||||||
if (prompt) body.prompt = prompt;
|
if (prompt) body.prompt = prompt;
|
||||||
if (image_url) body.image_url = image_url;
|
if (image_url) body.image = image_url; // OpenAI Videos 口径的参考图字段
|
||||||
|
if (seconds !== undefined) body.seconds = seconds;
|
||||||
|
if (aspect_ratio) body.aspect_ratio = aspect_ratio;
|
||||||
|
if (resolution) body.resolution = resolution;
|
||||||
|
if (negative_prompt) body.negative_prompt = negative_prompt;
|
||||||
|
if (enable_audio !== undefined) body.enable_audio = Boolean(enable_audio);
|
||||||
|
|
||||||
return await callZhipu({ url: ZHIPU_SUBMIT_URL, token, body });
|
return await callUpstream({ url: base + "/videos/generations", token, body });
|
||||||
// { model, id, request_id, task_status }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ===== op=get:查询异步结果(单次拉取,不内部轮询)=====
|
// ===== op=get:查询任务(单次拉取,不内部轮询)=====
|
||||||
async function queryAsyncResult({ token, id }) {
|
async function queryVideo({ base, token, taskId }) {
|
||||||
return await callZhipu({
|
return await callUpstream({
|
||||||
url: ZHIPU_QUERY_URL(id),
|
url: base + "/videos/" + encodeURIComponent(taskId),
|
||||||
token,
|
token,
|
||||||
method: "GET",
|
method: "GET",
|
||||||
});
|
});
|
||||||
// { id, request_id, model, task_status, video_result?, ... }
|
}
|
||||||
|
|
||||||
|
const DONE = new Set(["completed", "succeeded", "success"]);
|
||||||
|
const FAILED = new Set(["failed", "error", "cancelled", "canceled"]);
|
||||||
|
|
||||||
|
function normalizeStatus(s) {
|
||||||
|
return String(s || "").toLowerCase();
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------- op=create 的业务处理 ----------
|
// ---------- op=create 的业务处理 ----------
|
||||||
async function handleCreate({ args, headers, token }) {
|
async function handleCreate({ args, headers }) {
|
||||||
// 纯空白 prompt 等同没给:schema 只校验类型/长度,不校验内容。
|
// 纯空白 prompt 等同没给:schema 只校验类型/长度,不校验内容。
|
||||||
// 不 trim 的话,“ ”会被当成合法 prompt 提交(text-to-video 拿到空白提示词,
|
|
||||||
// image-to-video 则多传一个无意义字段)。
|
|
||||||
const prompt = typeof args.prompt === "string" ? args.prompt.trim() : "";
|
const prompt = typeof args.prompt === "string" ? args.prompt.trim() : "";
|
||||||
if (!prompt && !args.image_url) {
|
if (!prompt && !args.image_url) {
|
||||||
return {
|
return {
|
||||||
isError: true,
|
isError: true,
|
||||||
content: [
|
content: [{ type: "text", text: 'op=create requires at least one of "prompt" or "image_url".' }],
|
||||||
{
|
|
||||||
type: "text",
|
|
||||||
text: 'op=create requires at least one of "prompt" or "image_url".',
|
|
||||||
},
|
|
||||||
],
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// AI 不可见:全部走 header
|
let target;
|
||||||
const model = pickModel(headers) || DEFAULT_MODEL;
|
try {
|
||||||
const quality = pickHeaderString(
|
target = resolveTarget(headers);
|
||||||
headers,
|
} catch (e) {
|
||||||
"x-video-task-quality",
|
return { isError: true, content: [{ type: "text", text: e.message }] };
|
||||||
DEFAULT_QUALITY
|
}
|
||||||
);
|
|
||||||
const fps = pickHeaderInt(headers, "x-video-task-fps", DEFAULT_FPS);
|
|
||||||
const watermark_enabled = pickHeaderBool(
|
|
||||||
headers,
|
|
||||||
"x-video-task-watermark",
|
|
||||||
DEFAULT_WATERMARK_ENABLED
|
|
||||||
);
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const data = await submitVideo({
|
const data = await submitVideo({
|
||||||
token,
|
...target,
|
||||||
model,
|
|
||||||
prompt,
|
prompt,
|
||||||
image_url: args.image_url,
|
image_url: args.image_url,
|
||||||
quality,
|
seconds: args.seconds,
|
||||||
with_audio: args.with_audio ?? false,
|
aspect_ratio: args.aspect_ratio,
|
||||||
fps,
|
resolution: args.resolution,
|
||||||
watermark_enabled,
|
negative_prompt: args.negative_prompt,
|
||||||
|
enable_audio: args.enable_audio ?? args.with_audio,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const taskId = data.task_id || data.id;
|
||||||
const summary =
|
const summary =
|
||||||
`Model: ${model}\n` +
|
`task_id: ${taskId}\n` +
|
||||||
`task_id: ${data.id}\n` +
|
`model: ${target.model}\n` +
|
||||||
`request_id: ${data.request_id}\n` +
|
`status: ${data.status || "queued"}\n` +
|
||||||
`task_status: ${data.task_status}\n` +
|
|
||||||
`\n` +
|
`\n` +
|
||||||
`Video generation is asynchronous. ` +
|
`Video generation is asynchronous. ` +
|
||||||
`Call this tool again with op="get" and task_id="${data.id}" to fetch the result.`;
|
`Call this tool again with op="get" and task_id="${taskId}" to fetch the result.`;
|
||||||
|
|
||||||
return { content: [{ type: "text", text: summary }] };
|
return { content: [{ type: "text", text: summary }] };
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -251,9 +223,7 @@ async function handleCreate({ args, headers, token }) {
|
|||||||
content: [
|
content: [
|
||||||
{
|
{
|
||||||
type: "text",
|
type: "text",
|
||||||
text: `Failed to submit video task: ${e.message}${
|
text: `提交视频任务失败:${e.message}${e.detail ? `\nDetails: ${JSON.stringify(e.detail)}` : ""}`,
|
||||||
e.detail ? `\nDetails: ${JSON.stringify(e.detail)}` : ""
|
|
||||||
}`,
|
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
@@ -261,59 +231,51 @@ async function handleCreate({ args, headers, token }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ---------- op=get 的业务处理 ----------
|
// ---------- op=get 的业务处理 ----------
|
||||||
async function handleGet({ args, token }) {
|
async function handleGet({ args, headers }) {
|
||||||
// 与 handleCreate 同理:纯空白 task_id 不能直接拼进上游路径,
|
// 纯空白 task_id 不能直接拼进上游路径,否则得到一条含编码后空白的报错。
|
||||||
// 否则会得到一条含编码后空白的上游报错,既无从归因也误导模型。
|
|
||||||
const taskId = typeof args.task_id === "string" ? args.task_id.trim() : "";
|
const taskId = typeof args.task_id === "string" ? args.task_id.trim() : "";
|
||||||
if (!taskId) {
|
if (!taskId) {
|
||||||
return {
|
return { isError: true, content: [{ type: "text", text: 'op=get requires "task_id".' }] };
|
||||||
isError: true,
|
}
|
||||||
content: [{ type: "text", text: 'op=get requires "task_id".' }],
|
|
||||||
};
|
let target;
|
||||||
|
try {
|
||||||
|
target = resolveTarget(headers);
|
||||||
|
} catch (e) {
|
||||||
|
return { isError: true, content: [{ type: "text", text: e.message }] };
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const data = await queryAsyncResult({ token, id: taskId });
|
const data = await queryVideo({ ...target, taskId });
|
||||||
const status = data.task_status || "UNKNOWN";
|
const status = normalizeStatus(data.status);
|
||||||
|
|
||||||
if (status === "SUCCESS") {
|
if (DONE.has(status)) {
|
||||||
const v = (data.video_result || [])[0];
|
const url = (data.videos || [])[0]?.url || (data.data || [])[0]?.url;
|
||||||
if (!v || !v.url) {
|
if (!url) {
|
||||||
return {
|
return {
|
||||||
isError: true,
|
isError: true,
|
||||||
content: [
|
content: [{ type: "text", text: `任务已完成但没有视频地址。Raw: ${JSON.stringify(data).slice(0, 500)}` }],
|
||||||
{
|
|
||||||
type: "text",
|
|
||||||
text: `Task succeeded but no video URL returned. Raw: ${JSON.stringify(
|
|
||||||
data
|
|
||||||
)}`,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
const summary =
|
const credit = data.usage?.credit;
|
||||||
`task_id: ${data.id}\n` +
|
const text =
|
||||||
`model: ${data.model}\n` +
|
`task_id: ${taskId}\n` +
|
||||||
`task_status: SUCCESS\n` +
|
`model: ${data.model || target.model}\n` +
|
||||||
`Video URL: ${v.url}\n` +
|
`status: completed\n` +
|
||||||
(v.cover_image_url ? `Cover: ${v.cover_image_url}\n` : "");
|
`Video URL: ${url}\n` +
|
||||||
// 单块输出:URL 已经写在摘要里,旧版额外回一个裸 URL 块会让模型
|
(credit !== undefined ? `credit: ${credit}\n` : "") +
|
||||||
// (core 会把 text 块 join 成一段)看到同一个链接两遍。
|
(data.hint ? `note: ${data.hint}\n` : "");
|
||||||
return { content: [{ type: "text", text: summary }] };
|
return { content: [{ type: "text", text }] };
|
||||||
}
|
}
|
||||||
|
|
||||||
// PROCESSING / FAIL / 其他:原样返回关键字段
|
|
||||||
const errBlock = data.error ? `\nerror: ${JSON.stringify(data.error)}` : "";
|
const errBlock = data.error ? `\nerror: ${JSON.stringify(data.error)}` : "";
|
||||||
|
const progress = data.progress !== undefined ? `\nprogress: ${data.progress}` : "";
|
||||||
return {
|
return {
|
||||||
isError: status === "FAIL",
|
isError: FAILED.has(status),
|
||||||
content: [
|
content: [
|
||||||
{
|
{
|
||||||
type: "text",
|
type: "text",
|
||||||
text:
|
text: `task_id: ${taskId}\nmodel: ${data.model || target.model}\nstatus: ${data.status || "unknown"}${progress}${errBlock}`,
|
||||||
`task_id: ${data.id}\n` +
|
|
||||||
`model: ${data.model}\n` +
|
|
||||||
`task_status: ${status}` +
|
|
||||||
errBlock,
|
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
@@ -323,9 +285,7 @@ async function handleGet({ args, token }) {
|
|||||||
content: [
|
content: [
|
||||||
{
|
{
|
||||||
type: "text",
|
type: "text",
|
||||||
text: `Failed to query video task: ${e.message}${
|
text: `查询视频任务失败:${e.message}${e.detail ? `\nDetails: ${JSON.stringify(e.detail)}` : ""}`,
|
||||||
e.detail ? `\nDetails: ${JSON.stringify(e.detail)}` : ""
|
|
||||||
}`,
|
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
@@ -333,81 +293,61 @@ async function handleGet({ args, token }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function buildServer() {
|
function buildServer() {
|
||||||
const server = new McpServer(
|
const server = new McpServer({ name: "video_task", version: "2.0.0" }, { capabilities: { tools: {} } });
|
||||||
{ name: "video_task", version: "1.0.0" },
|
|
||||||
{ capabilities: { tools: {} } }
|
|
||||||
);
|
|
||||||
|
|
||||||
server.tool(
|
server.tool(
|
||||||
"video_task",
|
"video_task",
|
||||||
`AI video generation task.
|
`AI video generation task (async).
|
||||||
|
|
||||||
Operations:
|
Operations:
|
||||||
- \`create\`: Start a new video generation task. Requires at least one of \`prompt\` or \`image_url\`. Returns \`task_id\` immediately; generation runs in background.
|
- \`create\`: Start a new task. Requires at least one of \`prompt\` or \`image_url\`. Returns \`task_id\` immediately.
|
||||||
- \`get\`: Check an existing task. Requires \`task_id\`. Returns status and, on SUCCESS, the video URL.
|
- \`get\`: Check a task by \`task_id\`. Returns status and, when completed, the video URL.
|
||||||
|
|
||||||
Examples:
|
Examples:
|
||||||
- Text-to-video → \`{"op":"create","prompt":"A cat running in a garden"}\`
|
- Text-to-video → \`{"op":"create","prompt":"A cat running in a garden"}\`
|
||||||
- Image-to-video → \`{"op":"create","image_url":"https://example.com/cat.jpg","prompt":"The cat runs forward"}\`
|
- Image-to-video → \`{"op":"create","image_url":"https://example.com/cat.jpg","prompt":"The cat runs forward"}\`
|
||||||
- Check task → \`{"op":"get","task_id":"<task_id from create>"}\`
|
- Check task → \`{"op":"get","task_id":"<task_id from create>"}\`
|
||||||
|
|
||||||
Workflow: call \`create\` once, then call \`get\` with the returned \`task_id\` until \`task_status\` is \`SUCCESS\` or \`FAIL\`. Never create duplicate tasks just to check status.`,
|
Workflow: call \`create\` once, then call \`get\` with the returned \`task_id\` until status is \`completed\` or \`failed\`. Never create duplicate tasks just to check status.`,
|
||||||
{
|
{
|
||||||
op: z
|
op: z.enum(["create", "get"]).describe("create 提交生成;get 按 task_id 查结果。"),
|
||||||
.enum(["create", "get"])
|
|
||||||
.describe(
|
|
||||||
"Use create to start video generation; use get to check a task by its task_id."
|
|
||||||
),
|
|
||||||
prompt: z
|
prompt: z
|
||||||
.string()
|
.string()
|
||||||
.max(512)
|
.max(2000)
|
||||||
.optional()
|
.optional()
|
||||||
.describe(
|
.describe("视频描述,create 时 prompt 与 image_url 至少给一个。图生视频时描述画面如何运动。"),
|
||||||
"Video description, max 512 characters. Required for text-to-video; when combined with image_url it describes the motion."
|
|
||||||
),
|
|
||||||
image_url: z
|
image_url: z
|
||||||
.string()
|
.string()
|
||||||
.url()
|
.url()
|
||||||
.optional()
|
.optional()
|
||||||
.describe(
|
.describe(
|
||||||
"Reference image for image-to-video: publicly reachable png/jpeg/jpg URL <= 5 MB. For local files, first use the built-in mint_public_link tool to get a public temporary URL."
|
"参考图(图生视频):公开可访问的 png/jpeg URL。本地文件先用 agent 内置的公开临时 URL 工具换成短链。"
|
||||||
),
|
),
|
||||||
with_audio: z
|
seconds: z
|
||||||
.boolean()
|
.number()
|
||||||
.optional()
|
.int()
|
||||||
.describe(
|
|
||||||
"Whether to generate AI audio. Used with create; defaults to false."
|
|
||||||
),
|
|
||||||
task_id: z
|
|
||||||
.string()
|
|
||||||
.min(1)
|
.min(1)
|
||||||
|
.max(60)
|
||||||
.optional()
|
.optional()
|
||||||
.describe("task_id returned by create. Required for get; omit for create."),
|
.describe("视频时长(秒)。留空用上游默认;越长越慢越贵。"),
|
||||||
|
aspect_ratio: z.string().optional().describe("画幅,如 16:9 / 9:16 / 1:1。"),
|
||||||
|
resolution: z.string().optional().describe("分辨率,如 768P / 1080P。留空用上游默认。"),
|
||||||
|
negative_prompt: z.string().optional().describe("不希望出现的画面描述。"),
|
||||||
|
enable_audio: z.boolean().optional().describe("是否生成音频,默认 false。"),
|
||||||
|
with_audio: z.boolean().optional().describe("旧字段名,等同 enable_audio。"),
|
||||||
|
task_id: z.string().min(1).optional().describe("create 返回的 task_id,get 时必填。"),
|
||||||
},
|
},
|
||||||
async (args, extra) => {
|
async (args, extra) => {
|
||||||
const headers = extra?.requestInfo?.headers;
|
const headers = extra?.requestInfo?.headers;
|
||||||
const token = pickToken(headers);
|
|
||||||
if (!token) {
|
|
||||||
return {
|
|
||||||
isError: true,
|
|
||||||
content: [{ type: "text", text: "Missing authentication token." }],
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
switch (args.op) {
|
switch (args.op) {
|
||||||
case "create":
|
case "create":
|
||||||
return await handleCreate({ args, headers, token });
|
return await handleCreate({ args, headers });
|
||||||
case "get":
|
case "get":
|
||||||
return await handleGet({ args, token });
|
return await handleGet({ args, headers });
|
||||||
default:
|
default:
|
||||||
return {
|
return {
|
||||||
isError: true,
|
isError: true,
|
||||||
content: [
|
content: [{ type: "text", text: `Unknown op "${args.op}" (available: create, get).` }],
|
||||||
{
|
|
||||||
type: "text",
|
|
||||||
text: `Unknown op "${args.op}" (available: create, get).`,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -420,20 +360,14 @@ async function startHttp({ port, host }) {
|
|||||||
const app = express();
|
const app = express();
|
||||||
app.use(express.json({ limit: "2mb" }));
|
app.use(express.json({ limit: "2mb" }));
|
||||||
|
|
||||||
// session -> { server, transport } 映射
|
|
||||||
const sessions = new Map();
|
const sessions = new Map();
|
||||||
|
|
||||||
closeAllSessions = () => {
|
closeAllSessions = () => {
|
||||||
for (const { server, transport } of sessions.values()) {
|
for (const { server, transport } of sessions.values()) {
|
||||||
try {
|
try { transport.close(); } catch {}
|
||||||
transport.close();
|
try { server.close(); } catch {}
|
||||||
} catch {}
|
|
||||||
try {
|
|
||||||
server.close();
|
|
||||||
} catch {}
|
|
||||||
}
|
}
|
||||||
sessions.clear();
|
sessions.clear();
|
||||||
// 掰掉未关闭的 SSE / keep-alive 连接,否则 httpServer.close() 回调不会触发
|
|
||||||
httpServer?.closeAllConnections?.();
|
httpServer?.closeAllConnections?.();
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -444,22 +378,16 @@ async function startHttp({ port, host }) {
|
|||||||
async function handleSessionRequest(req, res) {
|
async function handleSessionRequest(req, res) {
|
||||||
const sessionId = req.headers["mcp-session-id"];
|
const sessionId = req.headers["mcp-session-id"];
|
||||||
|
|
||||||
// 已有 session:复用 transport
|
|
||||||
if (sessionId && sessions.has(sessionId)) {
|
if (sessionId && sessions.has(sessionId)) {
|
||||||
const { transport } = sessions.get(sessionId);
|
const { transport } = sessions.get(sessionId);
|
||||||
await transport.handleRequest(req, res, req.body);
|
await transport.handleRequest(req, res, req.body);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 新 session:必须是 initialize 请求
|
|
||||||
if (!isInitializeRequest(req.body)) {
|
if (!isInitializeRequest(req.body)) {
|
||||||
res.status(400).json({
|
res.status(400).json({
|
||||||
jsonrpc: "2.0",
|
jsonrpc: "2.0",
|
||||||
error: {
|
error: { code: -32000, message: "Bad Request: missing valid Mcp-Session-Id for non-initialize request" },
|
||||||
code: -32000,
|
|
||||||
message:
|
|
||||||
"Bad Request: missing valid Mcp-Session-Id for non-initialize request",
|
|
||||||
},
|
|
||||||
id: req.body?.id ?? null,
|
id: req.body?.id ?? null,
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
@@ -469,25 +397,19 @@ async function startHttp({ port, host }) {
|
|||||||
const server = buildServer();
|
const server = buildServer();
|
||||||
const transport = new StreamableHTTPServerTransport({
|
const transport = new StreamableHTTPServerTransport({
|
||||||
sessionIdGenerator: () => newId,
|
sessionIdGenerator: () => newId,
|
||||||
onsessioninitialized: (id) => {
|
onsessioninitialized: (id) => { sessions.set(id, { server, transport }); },
|
||||||
sessions.set(id, { server, transport });
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
|
|
||||||
transport.onclose = () => {
|
transport.onclose = () => {
|
||||||
if (transport.sessionId) {
|
if (transport.sessionId) sessions.delete(transport.sessionId);
|
||||||
sessions.delete(transport.sessionId);
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
await server.connect(transport);
|
await server.connect(transport);
|
||||||
await transport.handleRequest(req, res, req.body);
|
await transport.handleRequest(req, res, req.body);
|
||||||
}
|
}
|
||||||
|
|
||||||
// POST /mcp: 主入口
|
|
||||||
app.post("/mcp", handleSessionRequest);
|
app.post("/mcp", handleSessionRequest);
|
||||||
|
|
||||||
// GET /mcp & DELETE /mcp: 用于 SSE 流 / 会话关闭
|
|
||||||
const handleOther = async (req, res) => {
|
const handleOther = async (req, res) => {
|
||||||
const sessionId = req.headers["mcp-session-id"];
|
const sessionId = req.headers["mcp-session-id"];
|
||||||
if (!sessionId || !sessions.has(sessionId)) {
|
if (!sessionId || !sessions.has(sessionId)) {
|
||||||
@@ -501,17 +423,13 @@ async function startHttp({ port, host }) {
|
|||||||
app.delete("/mcp", handleOther);
|
app.delete("/mcp", handleOther);
|
||||||
|
|
||||||
httpServer = app.listen(port, host, () => {
|
httpServer = app.listen(port, host, () => {
|
||||||
console.log(
|
console.log(`[video] MCP HTTP server listening on http://${host}:${port}/mcp`);
|
||||||
`[video] MCP HTTP server listening on http://${host}:${port}/mcp`
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async function startStdio() {
|
async function startStdio() {
|
||||||
const server = buildServer();
|
const server = buildServer();
|
||||||
const { StdioServerTransport } = await import(
|
const { StdioServerTransport } = await import("@modelcontextprotocol/sdk/server/stdio.js");
|
||||||
"@modelcontextprotocol/sdk/server/stdio.js"
|
|
||||||
);
|
|
||||||
const transport = new StdioServerTransport();
|
const transport = new StdioServerTransport();
|
||||||
await server.connect(transport);
|
await server.connect(transport);
|
||||||
console.error("[video] MCP stdio server started");
|
console.error("[video] MCP stdio server started");
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
node_modules/
|
||||||
|
server.yml
|
||||||
|
client.yml
|
||||||
|
*.log
|
||||||
|
data/
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
FROM node:20-slim
|
||||||
|
|
||||||
|
ENV TZ=Asia/Shanghai
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# 国内构建慢:npm 默认源在国外。默认换成腾讯云镜像(与 app/Dockerfile 同源)。
|
||||||
|
# 境外构建或想换源:docker compose build --build-arg NPM_REGISTRY=https://registry.npmjs.org/
|
||||||
|
ARG NPM_REGISTRY=https://mirrors.cloud.tencent.com/npm/
|
||||||
|
|
||||||
|
# 只依赖 ws(纯 JS,无预编译二进制,不需要 better-sqlite3 那套 binary mirror 配置)
|
||||||
|
# 基础镜像与 app/Dockerfile 同版本(node:20-slim):服务器上已有,构建时不用再拉一遍
|
||||||
|
COPY package.json package-lock.json ./
|
||||||
|
RUN npm config set registry "$NPM_REGISTRY" \
|
||||||
|
&& npm install --omit=dev --no-audit --no-fund
|
||||||
|
|
||||||
|
COPY server.js ./
|
||||||
|
|
||||||
|
EXPOSE 19000
|
||||||
|
CMD ["node", "server.js"]
|
||||||
@@ -0,0 +1,190 @@
|
|||||||
|
# tunnel · 通用反向隧道
|
||||||
|
|
||||||
|
把本机(家里)的 HTTP 服务,经一台有公网 IP 的服务器中转出去。对访问方**完全透明**——
|
||||||
|
浏览器看到的仍是标准 HTTP/SSE,服务本身不需要任何改造。
|
||||||
|
|
||||||
|
```
|
||||||
|
手机/浏览器 ──https──> nginx:443 ──> server.js ──WebSocket──> client.js ──> 127.0.0.1:<port>
|
||||||
|
(服务器) (家里)
|
||||||
|
```
|
||||||
|
|
||||||
|
- **server.js** 不认识任何业务:只按 `Host` 头(或固定端口)把字节搬给 client
|
||||||
|
- **client.js** 按 `services` 配置把请求映射到本地端口
|
||||||
|
- 新增服务 = 改 client 配置一行,**两边代码都不用动**
|
||||||
|
|
||||||
|
## 启动顺序
|
||||||
|
|
||||||
|
没有严格要求。client 连不上会 1s→30s 指数退避重连,先起谁都能自动接上。
|
||||||
|
第一次配置建议先起 server,日志会直接告诉你 client 是否连上、token 对不对。
|
||||||
|
|
||||||
|
## 快速验证(本机,不碰 nginx)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd tunnel && npm install # 国内慢就加 --registry=https://registry.npmmirror.com
|
||||||
|
cp client.example.yml client.yml # server 改成 ws://127.0.0.1:19000/tunnel,token 先留空
|
||||||
|
node server.js & # 首次启动生成 server.yml,日志打印 TOKEN
|
||||||
|
# 把 TOKEN 填进 client.yml 的 token,再:
|
||||||
|
node client.js &
|
||||||
|
curl -H "Host: agent.home.example.com" http://127.0.0.1:19000/api/health
|
||||||
|
curl -s http://127.0.0.1:19000/__tunnel/health # {"ok":true,"client":"online",...}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 服务器部署
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd tunnel
|
||||||
|
docker compose up -d
|
||||||
|
docker compose logs | grep TOKEN # 首次启动自动生成,记下来填到家里 client.yml
|
||||||
|
```
|
||||||
|
|
||||||
|
**不需要先写配置**:首次启动会自动生成 `./data/server.yml`,里面带一个随机 token 并打印到日志。
|
||||||
|
第二次启动直接复用,token 不会变。
|
||||||
|
|
||||||
|
裸跑也行(不写配置同样自动生成):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
node server.js # 配置落在 ./server.yml
|
||||||
|
TUNNEL_CONFIG=/path/to/server.yml node server.js
|
||||||
|
```
|
||||||
|
|
||||||
|
## 请求怎么找到对应的服务
|
||||||
|
|
||||||
|
一台服务器、一个端口,请求进来后要决定「这个请求是给 agent 还是给 NAS」。三种做法:
|
||||||
|
|
||||||
|
### 1. 看域名(有域名时最自然)
|
||||||
|
|
||||||
|
```
|
||||||
|
agent.home.example.com → 家里 8090
|
||||||
|
nas.home.example.com → 家里 5000
|
||||||
|
```
|
||||||
|
|
||||||
|
隧道读请求里的 `Host` 头决定转发给谁。配置就是 `client.yml` 的 `host` 字段:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
services:
|
||||||
|
- host: agent.home.example.com
|
||||||
|
port: 8090
|
||||||
|
```
|
||||||
|
|
||||||
|
需要 DNS 泛解析 `*.home.example.com` 指到服务器,前面再套一层 nginx 做 TLS。
|
||||||
|
|
||||||
|
### 2. 一个端口钉一个服务(没有域名,又要多个服务)
|
||||||
|
|
||||||
|
隧道同时监听好几个端口,每个端口只认一个服务名:
|
||||||
|
|
||||||
|
```
|
||||||
|
http://<服务器IP>:19001 → 固定给 agent
|
||||||
|
http://<服务器IP>:19002 → 固定给 NAS
|
||||||
|
```
|
||||||
|
|
||||||
|
`server.yml` 声明端口归属:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
routes:
|
||||||
|
- port: 19001
|
||||||
|
service: agent
|
||||||
|
- port: 19002
|
||||||
|
service: nas
|
||||||
|
```
|
||||||
|
|
||||||
|
`client.yml` 用 `name` 对上:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
services:
|
||||||
|
- name: agent
|
||||||
|
port: 8090
|
||||||
|
- name: nas
|
||||||
|
port: 5000
|
||||||
|
```
|
||||||
|
|
||||||
|
`docker-compose.yml` 里把 19001/19002 的 `ports` 放开。**完全不看 Host 头**。
|
||||||
|
|
||||||
|
### 3. 一个端口 + 通配(没有域名,只有一个服务)
|
||||||
|
|
||||||
|
最简单:所有请求都给同一个服务。
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
services:
|
||||||
|
- host: "*"
|
||||||
|
port: 8090
|
||||||
|
```
|
||||||
|
|
||||||
|
浏览器开 `http://<服务器IP>:19000` 就是它。
|
||||||
|
|
||||||
|
### 怎么选
|
||||||
|
|
||||||
|
| 你的情况 | 用哪个 |
|
||||||
|
|---|---|
|
||||||
|
| 有域名 | 方式 1 |
|
||||||
|
| 没域名,只暴露一个服务 | 方式 3(一行配置) |
|
||||||
|
| 没域名,要暴露多个服务 | 方式 2(一个服务一个端口) |
|
||||||
|
|
||||||
|
方式 1 和 2 **可以同时开**:19000 走 Host 路由,19001/19002 各钉死一个服务,互不干扰。
|
||||||
|
|
||||||
|
## 家里部署
|
||||||
|
|
||||||
|
```bash
|
||||||
|
node client.js # 读同目录 client.yml
|
||||||
|
node client.js /path/to/client.yml
|
||||||
|
```
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
server: "wss://agent.home.example.com/tunnel"
|
||||||
|
token: "<和服务器同一个>"
|
||||||
|
userAgent: "Mozilla/5.0 (...) Chrome/131.0.0.0 Safari/537.36"
|
||||||
|
services:
|
||||||
|
- name: agent
|
||||||
|
host: agent.home.example.com
|
||||||
|
port: 8090
|
||||||
|
```
|
||||||
|
|
||||||
|
- `name`:固定端口路由用的服务标识(有域名时可省略)
|
||||||
|
- `host`:`域名` / `*.example.com` / `"*"`(兜底)
|
||||||
|
- `userAgent`:可选,握手时伪装浏览器 UA,降低被 DPI 盯上的概率
|
||||||
|
- 断线自动重连(含半死链路:75 秒收不到任何帧即主动断开重连),启动时自检每个端口可达性(不可达只告警不退出)
|
||||||
|
|
||||||
|
## 隧道协议
|
||||||
|
|
||||||
|
一条 WebSocket 承载所有请求,用 `id` 多路复用。
|
||||||
|
|
||||||
|
```jsonc
|
||||||
|
// 服务器 → 家里
|
||||||
|
{"id":"r1","op":"req","method":"POST","path":"/api/x","headers":{...},"service":"agent"}
|
||||||
|
{"id":"r1","op":"body","b64":"..."} // 请求体分帧
|
||||||
|
{"id":"r1","op":"end"}
|
||||||
|
{"id":"r1","op":"abort"} // 浏览器提前断开
|
||||||
|
|
||||||
|
// 家里 → 服务器(响应分帧,边收边转)
|
||||||
|
{"id":"r1","ev":"head","status":200,"headers":{...}}
|
||||||
|
{"id":"r1","ev":"data","b64":"..."}
|
||||||
|
{"id":"r1","ev":"end"}
|
||||||
|
{"id":"r1","ev":"error","msg":"..."}
|
||||||
|
```
|
||||||
|
|
||||||
|
`service` 只在「固定端口路由」时出现;没有它 client 就按 Host 头匹配。
|
||||||
|
|
||||||
|
## 已知边界
|
||||||
|
|
||||||
|
| 能力 | 状态 |
|
||||||
|
|---|---|
|
||||||
|
| 普通 HTTP / 大 body(测过 27 MB) | ✅ |
|
||||||
|
| SSE / 流式响应 | ✅ 逐帧透传(800ms/帧测试,间隔与直连一致) |
|
||||||
|
| 重定向(302) | ✅ 原样透传,不在隧道里跟跳 |
|
||||||
|
| 未知 Host | 502 |
|
||||||
|
| client 离线 | 503(快速失败,不挂住) |
|
||||||
|
| 固定端口路由 / `*` 通配 | ✅ |
|
||||||
|
| **WebSocket 升级** | ❌ 未实现(需双向字节流,二期) |
|
||||||
|
| HTTP/2 | ❌ 对外仍是 1.1,影响不大 |
|
||||||
|
|
||||||
|
## 排错
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -s http://127.0.0.1:19000/__tunnel/health # client 在不在线
|
||||||
|
tail -f /tmp/tunnel-client.log # 家里端
|
||||||
|
tail -f /tmp/tunnel-server.log # 服务器端
|
||||||
|
```
|
||||||
|
|
||||||
|
- **502 没有匹配的本地服务**:`services[].host` 和请求 Host 不一致;无域名时用 `"*"` 或固定端口
|
||||||
|
- **SSE 憋着不出来**:nginx 少了 `proxy_buffering off`
|
||||||
|
- **大 body 报 `expect header not supported`**:旧版本才有,client 现在会剥掉 `Expect` 头
|
||||||
|
- **握手 401**:两边 token 不一致
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
# tunnel 本机端配置 —— 复制为 client.yml 后改(client.yml 不进版本库)
|
||||||
|
|
||||||
|
# 服务器隧道地址,两种形态按需选:
|
||||||
|
# 只有 IP(最省事,但要求服务器把 19000 映射到 0.0.0.0)
|
||||||
|
# ws://1.2.3.4:19000/tunnel ← 明文,token 在公网裸奔,仅限内网/临时调试
|
||||||
|
# 有域名 + 证书(推荐,前面套 nginx 反代)
|
||||||
|
# wss://tunnel.example.com/tunnel
|
||||||
|
server: "ws://1.2.3.4:19000/tunnel"
|
||||||
|
|
||||||
|
# 和服务器 server.yml 里自动生成的 token 一致
|
||||||
|
token: ""
|
||||||
|
|
||||||
|
# 握手 UA:伪装成浏览器,降低被 DPI 盯上的概率。不写就用内置默认值
|
||||||
|
# userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
|
||||||
|
|
||||||
|
# 请求体上限(MB),和服务端双保险
|
||||||
|
maxBodyMb: 64
|
||||||
|
|
||||||
|
# 要暴露的本地服务:加服务 = 加一项,两边代码都不用动
|
||||||
|
# 路由优先级:固定端口指定的 name → host 精确 → *.域名 通配 → "*" 兜底
|
||||||
|
services:
|
||||||
|
# 直接按 IP 访问时,请求的 Host 头就是那个 IP,用 "*" 兜底最省事(单服务形态)
|
||||||
|
- host: "*"
|
||||||
|
port: 8090
|
||||||
|
|
||||||
|
# 有域名时按 Host 精确匹配,一个域名对一个服务
|
||||||
|
# - name: agent
|
||||||
|
# host: agent.example.com
|
||||||
|
# port: 8090
|
||||||
|
# - name: nas
|
||||||
|
# host: nas.example.com
|
||||||
|
# port: 5000
|
||||||
@@ -0,0 +1,241 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
'use strict';
|
||||||
|
// 通用反向隧道 · 本机端(家里那台)
|
||||||
|
// 主动连服务器 → 收请求 → 按 Host 找本地端口 → 转发 → 流式回传
|
||||||
|
//
|
||||||
|
// 用法: node client.js [config.yml] 环境变量 TUNNEL_SERVER / TUNNEL_TOKEN 覆盖配置
|
||||||
|
// 断线自动重连(指数退避 1s → 30s)。心跳由服务端 ping 驱动、本端 ws 库自动回 pong;
|
||||||
|
// 但半死链路(Mac 睡眠/切网后 TCP 还在、实际不通)不会触发 close,所以本端另设看门狗。
|
||||||
|
|
||||||
|
const fs = require('node:fs');
|
||||||
|
const path = require('node:path');
|
||||||
|
const http = require('node:http');
|
||||||
|
const zlib = require('node:zlib');
|
||||||
|
const YAML = require('yaml');
|
||||||
|
const WebSocket = require('ws');
|
||||||
|
|
||||||
|
// ---------- 配置 ----------
|
||||||
|
function loadConfig() {
|
||||||
|
const file = process.argv[2] || path.join(__dirname, 'client.yml');
|
||||||
|
let cfg = {};
|
||||||
|
if (fs.existsSync(file)) {
|
||||||
|
try { cfg = YAML.parse(fs.readFileSync(file, 'utf8')) || {}; } catch (e) {
|
||||||
|
console.error('[tunnel] ' + file + ' 不是合法 YAML:' + e.message);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cfg.server = String(process.env.TUNNEL_SERVER || cfg.server || '').trim();
|
||||||
|
cfg.token = String(process.env.TUNNEL_TOKEN || cfg.token || '').trim();
|
||||||
|
cfg.services = Array.isArray(cfg.services) ? cfg.services : [];
|
||||||
|
// 默认 UA 伪装成浏览器:跨境链路上「frp/x.x」这种 UA 是明显特征
|
||||||
|
cfg.userAgent = cfg.userAgent ||
|
||||||
|
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0 Safari/537.36';
|
||||||
|
cfg.maxBodyMb = Number(cfg.maxBodyMb || 64);
|
||||||
|
if (!cfg.server || !cfg.token) {
|
||||||
|
console.error('[tunnel] 需要 server 和 token:写进 client.yml,或设 TUNNEL_SERVER / TUNNEL_TOKEN');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
if (!cfg.services.length) {
|
||||||
|
console.error('[tunnel] services 为空:至少配一项 {host, port}');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
return cfg;
|
||||||
|
}
|
||||||
|
const CFG = loadConfig();
|
||||||
|
|
||||||
|
// 日志时间固定东八区:本机时区可能变,跨时区看日志不该换算
|
||||||
|
const CST_MS = 8 * 3600 * 1000;
|
||||||
|
function log(...a) { console.log(new Date(Date.now() + CST_MS).toISOString().slice(11, 19), '[client]', ...a); }
|
||||||
|
|
||||||
|
// ---------- 服务路由:Host → 本地端口 ----------
|
||||||
|
// 精确匹配优先;再退到「忽略端口」;最后允许 *.xxx 通配一项
|
||||||
|
// 服务匹配优先级:固定端口指定的 name → host 精确 → *.域名 通配 → "*" 兜底
|
||||||
|
// "*" 是给「服务器没有域名」的场景用的:浏览器访问 http://1.2.3.4:19000,
|
||||||
|
// Host 头是 IP,对不上任何域名,此时所有请求都交给这个服务(单服务形态)。
|
||||||
|
function pickService(meta) {
|
||||||
|
const list = CFG.services || [];
|
||||||
|
if (meta.service) {
|
||||||
|
const byName = list.find(s => String(s.name || '') === String(meta.service));
|
||||||
|
if (byName) return byName;
|
||||||
|
}
|
||||||
|
const host = String((meta.headers && meta.headers.host) || '').toLowerCase().split(':')[0];
|
||||||
|
for (const s of list) if (String(s.host || '').toLowerCase() === host) return s;
|
||||||
|
for (const s of list) {
|
||||||
|
const h = String(s.host || '').toLowerCase();
|
||||||
|
if (h.startsWith('*.') && host.endsWith(h.slice(1))) return s;
|
||||||
|
}
|
||||||
|
for (const s of list) if (s.host === '*') return s;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 在途请求 ----------
|
||||||
|
// 收到 op=req 建条目,body 帧往里堆,op=end 才真正发出去;
|
||||||
|
// op=abort(手机提前断开)→ abort 本地请求,别让上游白跑。
|
||||||
|
const inflight = new Map();
|
||||||
|
let ws = null;
|
||||||
|
let backoff = 1000;
|
||||||
|
let stopping = false;
|
||||||
|
let lastSeen = 0; // 最近一次收到服务端任何帧的时刻
|
||||||
|
|
||||||
|
function send(obj) {
|
||||||
|
if (ws && ws.readyState === 1) {
|
||||||
|
try { ws.send(JSON.stringify(obj)); } catch (_) {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function onMessage(raw) {
|
||||||
|
let m;
|
||||||
|
try { m = JSON.parse(raw); } catch (_) { return; }
|
||||||
|
if (m.op === 'req') {
|
||||||
|
inflight.set(m.id, { meta: m, chunks: [], size: 0, ac: new AbortController() });
|
||||||
|
} else if (m.op === 'body') {
|
||||||
|
const st = inflight.get(m.id);
|
||||||
|
if (!st) return;
|
||||||
|
const buf = Buffer.from(m.b64 || '', 'base64');
|
||||||
|
st.size += buf.length;
|
||||||
|
if (st.size > CFG.maxBodyMb * 1048576) { // 和服务端同一个上限,双保险
|
||||||
|
st.ac.abort();
|
||||||
|
inflight.delete(m.id);
|
||||||
|
return send({ id: m.id, ev: 'error', msg: 'body too large' });
|
||||||
|
}
|
||||||
|
st.chunks.push(buf);
|
||||||
|
} else if (m.op === 'end') {
|
||||||
|
const st = inflight.get(m.id);
|
||||||
|
if (!st) return;
|
||||||
|
inflight.delete(m.id);
|
||||||
|
handleRequest(m.id, st);
|
||||||
|
} else if (m.op === 'abort') {
|
||||||
|
const st = inflight.get(m.id);
|
||||||
|
if (st) { st.ac.abort(); inflight.delete(m.id); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// gzip 阈值:小于 1KB 压了反而亏(gzip 头开销),超过 8MB 不进内存直接流式
|
||||||
|
const COMPRESSIBLE = /^(text\/|application\/(json|javascript|xml|x-javascript)|image\/svg)/i;
|
||||||
|
const GZ_MIN = 1024;
|
||||||
|
const GZ_MAX = 8 * 1024 * 1024;
|
||||||
|
|
||||||
|
async function handleRequest(id, st) {
|
||||||
|
const { meta, chunks, ac } = st;
|
||||||
|
const svc = pickService(meta);
|
||||||
|
if (!svc) {
|
||||||
|
return send({ id, ev: 'error', msg: '没有匹配的本地服务: host=' + ((meta.headers || {}).host || '?') });
|
||||||
|
}
|
||||||
|
|
||||||
|
const headers = {};
|
||||||
|
for (const [k, v] of Object.entries(meta.headers || {})) {
|
||||||
|
const lk = k.toLowerCase();
|
||||||
|
if (lk === 'host' || lk === 'connection' || lk === 'content-length' || lk === 'expect') continue;
|
||||||
|
headers[k] = v;
|
||||||
|
}
|
||||||
|
// 强制不压缩:本端 fetch 会自动解压响应体,若保留 gzip 头,下游浏览器会拿明文当压缩流解析
|
||||||
|
headers['accept-encoding'] = 'identity';
|
||||||
|
|
||||||
|
const body = chunks.length ? Buffer.concat(chunks) : undefined;
|
||||||
|
try {
|
||||||
|
const r = await fetch('http://127.0.0.1:' + svc.port + meta.path, {
|
||||||
|
method: meta.method,
|
||||||
|
headers,
|
||||||
|
body,
|
||||||
|
signal: ac.signal,
|
||||||
|
redirect: 'manual', // 302 要原样交给浏览器,别在这里跟丢
|
||||||
|
});
|
||||||
|
const outHeaders = {};
|
||||||
|
r.headers.forEach((v, k) => { outHeaders[k] = v; });
|
||||||
|
const ct = String(outHeaders['content-type'] || '');
|
||||||
|
const cl = Number(outHeaders['content-length']) || 0;
|
||||||
|
delete outHeaders['content-encoding']; // 体已被 fetch 解压,长度也对不上,统一走 chunked
|
||||||
|
delete outHeaders['content-length'];
|
||||||
|
delete outHeaders['transfer-encoding'];
|
||||||
|
|
||||||
|
// 可压缩、大小已知且在阈值内:缓冲后 gzip 再发。跨境链路上带宽是瓶颈,
|
||||||
|
// JS/CSS/JSON 能压到 1/4 左右。SSE 不能缓冲(会毁掉流式),大文件不进内存,
|
||||||
|
// 已压缩的二进制(图片/zip)压了反而变大——这几种都走下面的原路径。
|
||||||
|
if (COMPRESSIBLE.test(ct) && !/event-stream/i.test(ct) && cl > 0 && cl <= GZ_MAX) {
|
||||||
|
const buf = Buffer.from(await r.arrayBuffer());
|
||||||
|
const gz = buf.length >= GZ_MIN ? zlib.gzipSync(buf, { level: 6 }) : null;
|
||||||
|
if (gz && gz.length < buf.length * 0.9) { // 压不动(已压缩/随机数据)就发明文
|
||||||
|
outHeaders['content-encoding'] = 'gzip';
|
||||||
|
send({ id, ev: 'head', status: r.status, headers: outHeaders });
|
||||||
|
send({ id, ev: 'data', b64: gz.toString('base64') });
|
||||||
|
} else {
|
||||||
|
send({ id, ev: 'head', status: r.status, headers: outHeaders });
|
||||||
|
send({ id, ev: 'data', b64: buf.toString('base64') });
|
||||||
|
}
|
||||||
|
send({ id, ev: 'end' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
send({ id, ev: 'head', status: r.status, headers: outHeaders });
|
||||||
|
if (r.body) {
|
||||||
|
for await (const chunk of r.body) send({ id, ev: 'data', b64: Buffer.from(chunk).toString('base64') });
|
||||||
|
}
|
||||||
|
send({ id, ev: 'end' });
|
||||||
|
} catch (e) {
|
||||||
|
if (ac.signal.aborted) return; // 对端主动取消,不算错误
|
||||||
|
send({ id, ev: 'error', msg: (e.message || String(e)) + (e.cause ? ' | cause: ' + (e.cause.message || e.cause) : '') });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 连接 / 重连 ----------
|
||||||
|
// 日志只在状态变化时说:启动一条、连上一条、断开一条,重试过程完全静默
|
||||||
|
// (和 MCP 服务一个风格:启动时报一次自己在哪,之后没人连也不刷屏)。
|
||||||
|
let linked = false; // 当前是否连着
|
||||||
|
let everLinked = false; // 是否连上过(区分首连和重连)
|
||||||
|
|
||||||
|
function connect() {
|
||||||
|
if (stopping) return;
|
||||||
|
const sep = CFG.server.includes('?') ? '&' : '?';
|
||||||
|
const url = CFG.server + sep + 'token=' + encodeURIComponent(CFG.token);
|
||||||
|
ws = new WebSocket(url, {
|
||||||
|
headers: { 'User-Agent': CFG.userAgent },
|
||||||
|
handshakeTimeout: 20000,
|
||||||
|
perMessageDeflate: false, // 关压缩:SSE 小帧多,压缩反而添乱且增加特征
|
||||||
|
});
|
||||||
|
|
||||||
|
ws.on('open', () => {
|
||||||
|
backoff = 1000;
|
||||||
|
linked = true;
|
||||||
|
lastSeen = Date.now();
|
||||||
|
log(everLinked ? '已重新连接' : '已连接 ' + CFG.server);
|
||||||
|
everLinked = true;
|
||||||
|
});
|
||||||
|
ws.on('message', (data) => { lastSeen = Date.now(); onMessage(data); });
|
||||||
|
ws.on('ping', () => { lastSeen = Date.now(); });
|
||||||
|
ws.on('close', (code, reason) => {
|
||||||
|
if (stopping) return;
|
||||||
|
if (linked) { // 只在「连着 → 断开」这个跳变上说一次
|
||||||
|
linked = false;
|
||||||
|
log('断开' + (reason ? ':' + reason : '') + ',重连中');
|
||||||
|
}
|
||||||
|
setTimeout(connect, backoff);
|
||||||
|
backoff = Math.min(backoff * 2, 30000); // 指数退避,封顶 30s
|
||||||
|
});
|
||||||
|
ws.on('error', () => {}); // close 紧接着会来,不重复报
|
||||||
|
}
|
||||||
|
|
||||||
|
// 看门狗:服务端每 25s ping 一次,超过 75s(连丢 3 次)一个帧都没收到就认定链路半死。
|
||||||
|
// 这种连接 close 事件永远不来,只能本端主动 terminate,由 close 走既有重连。
|
||||||
|
setInterval(() => {
|
||||||
|
if (stopping || !ws || ws.readyState !== 1) return;
|
||||||
|
if (Date.now() - lastSeen > 75000) {
|
||||||
|
log('链路 ' + Math.round((Date.now() - lastSeen) / 1000) + 's 无响应,主动断开重连');
|
||||||
|
try { ws.terminate(); } catch (_) {}
|
||||||
|
}
|
||||||
|
}, 20000).unref();
|
||||||
|
|
||||||
|
process.on('SIGINT', () => { stopping = true; log('退出'); try { ws && ws.close(1000, 'client shutdown'); } catch (_) {} process.exit(0); });
|
||||||
|
process.on('SIGTERM', () => { stopping = true; process.exit(0); });
|
||||||
|
|
||||||
|
// 启动:一条说清楚往哪连、暴露了什么(之后只在状态变化时再说)
|
||||||
|
log('隧道 → ' + CFG.server + '(' + CFG.services.map(s => s.host + '→127.0.0.1:' + s.port).join(', ') + ')');
|
||||||
|
|
||||||
|
// 本地端口不通时早点说(只报问题,正常不吭声)
|
||||||
|
for (const s of CFG.services) {
|
||||||
|
const req = http.request({ host: '127.0.0.1', port: s.port, path: '/', method: 'HEAD', timeout: 3000 }, (res) => res.resume());
|
||||||
|
req.on('error', (e) => log('警告:127.0.0.1:' + s.port + ' 不可达(' + e.code + '),本地服务没起来?'));
|
||||||
|
req.on('timeout', () => { req.destroy(); log('警告:127.0.0.1:' + s.port + ' 超时'); });
|
||||||
|
req.end();
|
||||||
|
}
|
||||||
|
|
||||||
|
connect();
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
# tunnel 独立编排:只跑隧道服务端,和 agent 的 compose 互不相干
|
||||||
|
# cd tunnel && docker compose up -d
|
||||||
|
#
|
||||||
|
# 首次启动会自己生成 ./data/server.yml(含随机 token)并打印到日志:
|
||||||
|
# docker compose logs | grep TOKEN
|
||||||
|
# 把那个 token 填到家里 client.yml 的 token 即可。
|
||||||
|
services:
|
||||||
|
tunnel:
|
||||||
|
build: .
|
||||||
|
image: agent-tunnel:latest
|
||||||
|
container_name: agent-tunnel
|
||||||
|
restart: unless-stopped
|
||||||
|
ports:
|
||||||
|
# IP 直连:http://<服务器IP>:19000
|
||||||
|
- "${TUNNEL_PORT:-19000}:19000"
|
||||||
|
# 固定端口路由(一个端口钉一个服务):先在 data/server.yml 的 routes 里配好,再放开对应端口
|
||||||
|
# - "${TUNNEL_PORT_AGENT:-19001}:19001"
|
||||||
|
# - "${TUNNEL_PORT_NAS:-19002}:19002"
|
||||||
|
volumes:
|
||||||
|
# 挂目录而不是单文件:server.yml 不存在时 docker 会造个同名目录,单文件挂载会踩这个坑
|
||||||
|
- ./data:/app/data
|
||||||
|
environment:
|
||||||
|
- TZ=Asia/Shanghai
|
||||||
|
- TUNNEL_CONFIG=/app/data/server.yml
|
||||||
Generated
+48
@@ -0,0 +1,48 @@
|
|||||||
|
{
|
||||||
|
"name": "agent-tunnel",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"lockfileVersion": 3,
|
||||||
|
"requires": true,
|
||||||
|
"packages": {
|
||||||
|
"": {
|
||||||
|
"name": "agent-tunnel",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"dependencies": {
|
||||||
|
"ws": "8.23.0",
|
||||||
|
"yaml": "2.6.1"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/ws": {
|
||||||
|
"version": "8.23.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/ws/-/ws-8.23.0.tgz",
|
||||||
|
"integrity": "sha512-wCkmX8QMOrKjgO8HW2WyDbTSGeqkocxgDzS9iR79rEAexty6/2qzilx3Ag8Tqf9ykop3irLKle0MtVn5qjVnoQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=10.0.0"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"bufferutil": "^4.0.1",
|
||||||
|
"utf-8-validate": ">=5.0.2"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"bufferutil": {
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"utf-8-validate": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/yaml": {
|
||||||
|
"version": "2.6.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/yaml/-/yaml-2.6.1.tgz",
|
||||||
|
"integrity": "sha512-7r0XPzioN/Q9kXBro/XPnA6kznR73DHq+GXh5ON7ZozRO6aMjbmiBuKste2wslTFkC5d1dw0GooOCepZXJ2SAg==",
|
||||||
|
"bin": {
|
||||||
|
"yaml": "bin.mjs"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 14"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
{
|
||||||
|
"name": "agent-tunnel",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"private": true,
|
||||||
|
"description": "通用反向隧道:把本机 HTTP 服务经服务器中转,按 Host 路由,支持流式响应",
|
||||||
|
"main": "server.js",
|
||||||
|
"scripts": {
|
||||||
|
"server": "node server.js",
|
||||||
|
"client": "node client.js"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"ws": "8.23.0",
|
||||||
|
"yaml": "2.6.1"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,257 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
'use strict';
|
||||||
|
// 通用反向隧道 · 服务器端
|
||||||
|
// 浏览器/手机 ──https──> nginx ──> 本进程 ──WebSocket──> 本机(家里) client ──> 127.0.0.1:port
|
||||||
|
//
|
||||||
|
// 本进程不认识任何业务:只按请求的 Host 头把字节搬给 client,client 再按自己的
|
||||||
|
// services 配置找本地端口。所以任何 HTTP 服务接进来都不用改这里的代码。
|
||||||
|
//
|
||||||
|
// 用法: node server.js [config.yml] 环境变量 TUNNEL_PORT / TUNNEL_TOKEN 覆盖配置
|
||||||
|
// 协议: 见 README.md「隧道协议」一节
|
||||||
|
|
||||||
|
const http = require('node:http');
|
||||||
|
const fs = require('node:fs');
|
||||||
|
const crypto = require('node:crypto');
|
||||||
|
const path = require('node:path');
|
||||||
|
const YAML = require('yaml');
|
||||||
|
const { WebSocketServer } = require('ws');
|
||||||
|
|
||||||
|
// ---------- 配置 ----------
|
||||||
|
function loadConfig() {
|
||||||
|
const file = process.env.TUNNEL_CONFIG || process.argv[2] || path.join(__dirname, 'server.yml');
|
||||||
|
let cfg = {};
|
||||||
|
let dirty = false;
|
||||||
|
if (fs.existsSync(file)) {
|
||||||
|
try { cfg = YAML.parse(fs.readFileSync(file, 'utf8')) || {}; } catch (e) {
|
||||||
|
console.error('[tunnel] ' + file + ' 不是合法 YAML:' + e.message);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
dirty = true; // 没有配置文件 → 首次启动
|
||||||
|
}
|
||||||
|
cfg.port = Number(process.env.TUNNEL_PORT || cfg.port || 19000);
|
||||||
|
cfg.token = String(process.env.TUNNEL_TOKEN || cfg.token || '');
|
||||||
|
cfg.maxBodyMb = Number(cfg.maxBodyMb || 64);
|
||||||
|
cfg.heartbeatMs = Number(cfg.heartbeatMs || 25000);
|
||||||
|
|
||||||
|
// 没 token 就现生成一个随机串并落盘:省掉「先手写配置再启动」这一步,
|
||||||
|
// docker compose up -d 直接就能跑。落盘失败也不阻断(本次仍可用)。
|
||||||
|
if (!cfg.token) {
|
||||||
|
cfg.token = crypto.randomBytes(24).toString('base64url');
|
||||||
|
dirty = true;
|
||||||
|
}
|
||||||
|
if (dirty) {
|
||||||
|
try {
|
||||||
|
fs.mkdirSync(path.dirname(file), { recursive: true });
|
||||||
|
const out = { port: cfg.port, token: cfg.token, maxBodyMb: cfg.maxBodyMb, heartbeatMs: cfg.heartbeatMs };
|
||||||
|
if (Array.isArray(cfg.routes) && cfg.routes.length) out.routes = cfg.routes;
|
||||||
|
// 写回带注释的模板:YAML.stringify 本身会丢掉注释,头部这几行手动拼。
|
||||||
|
// 这份自动生成的 server.yml 就是字段说明的唯一出处(不另维护示例文件)。
|
||||||
|
const head = '# tunnel 服务端配置(首次启动自动生成,可直接改,改完重启生效)\n'
|
||||||
|
+ '# port 本端口,按 Host 头路由\n'
|
||||||
|
+ '# token 必须和家里 client.yml 里的一致\n'
|
||||||
|
+ '# maxBodyMb 单请求体上限(MB)\n'
|
||||||
|
+ '# heartbeatMs 心跳间隔(ms),跨境链路靠它发现半死连接\n'
|
||||||
|
+ '# routes 可选,固定端口路由:一个端口钉死一个服务(每个 port 还要在\n'
|
||||||
|
+ '# docker-compose.yml 的 ports 里放开)。写法:\n'
|
||||||
|
+ '# routes:\n'
|
||||||
|
+ '# - port: 19001\n'
|
||||||
|
+ '# service: agent\n';
|
||||||
|
fs.writeFileSync(file, head + YAML.stringify(out));
|
||||||
|
console.log('============================================================');
|
||||||
|
console.log(' 首次启动,已生成配置:' + file);
|
||||||
|
console.log(' TOKEN: ' + cfg.token);
|
||||||
|
console.log(' ↑ 填到家里 client.yml 的 token,然后重启 client');
|
||||||
|
console.log('============================================================');
|
||||||
|
} catch (e) {
|
||||||
|
console.error('[tunnel] 写配置失败:' + e.message + '(本次 token 仅进程内有效)');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return cfg;
|
||||||
|
}
|
||||||
|
const CFG = loadConfig();
|
||||||
|
|
||||||
|
// ---------- 连接状态 ----------
|
||||||
|
let client = null; // 家里那条 WS(只允许一条,新的顶掉旧的)
|
||||||
|
const pending = new Map(); // id -> { res, timer }
|
||||||
|
let seq = 0;
|
||||||
|
const nextId = () => 'r' + (++seq).toString(36) + Math.random().toString(36).slice(2, 6);
|
||||||
|
|
||||||
|
// 逐跳头:只对单段连接有意义,不能透传
|
||||||
|
const HOP_BY_HOP = new Set(['connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization',
|
||||||
|
'te', 'trailer', 'transfer-encoding', 'upgrade']);
|
||||||
|
|
||||||
|
function log(...a) { console.log(new Date().toISOString().slice(11, 19), '[server]', ...a); }
|
||||||
|
|
||||||
|
// ---------- HTTP:把请求搬给 client ----------
|
||||||
|
// fixedService:由「固定端口路由」传进来(无域名时一个端口对一个服务);null = 按 Host 头路由
|
||||||
|
function handleRequest(req, res, fixedService) {
|
||||||
|
// 健康检查:只在主端口答,固定端口一律当业务流量转走
|
||||||
|
if (!fixedService && req.url === '/__tunnel/health') {
|
||||||
|
return json(res, 200, {
|
||||||
|
ok: true,
|
||||||
|
client: client ? 'online' : 'offline',
|
||||||
|
pending: pending.size,
|
||||||
|
uptime_s: Math.round(process.uptime()),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!client || client.readyState !== 1) {
|
||||||
|
return json(res, 503, { error: 'tunnel client offline', hint: '家里那台没连上,或 token 不对' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const id = nextId();
|
||||||
|
const headers = {};
|
||||||
|
for (const [k, v] of Object.entries(req.headers)) if (!HOP_BY_HOP.has(k)) headers[k] = v;
|
||||||
|
|
||||||
|
pending.set(id, { res, timer: null });
|
||||||
|
const frame = { id, op: 'req', method: req.method, path: req.url, headers };
|
||||||
|
if (fixedService) frame.service = fixedService; // 端口绑定的服务名,client 优先按它找
|
||||||
|
client.send(JSON.stringify(frame));
|
||||||
|
|
||||||
|
let size = 0;
|
||||||
|
let overflow = false;
|
||||||
|
req.on('data', (chunk) => {
|
||||||
|
if (overflow) return;
|
||||||
|
size += chunk.length;
|
||||||
|
if (size > CFG.maxBodyMb * 1048576) { // 超限直接掐,别把内存吃穿
|
||||||
|
overflow = true;
|
||||||
|
client.send(JSON.stringify({ id, op: 'abort' }));
|
||||||
|
pending.delete(id);
|
||||||
|
return json(res, 413, { error: 'body too large', limit_mb: CFG.maxBodyMb });
|
||||||
|
}
|
||||||
|
client.send(JSON.stringify({ id, op: 'body', b64: chunk.toString('base64') }));
|
||||||
|
});
|
||||||
|
req.on('end', () => { if (!overflow) client.send(JSON.stringify({ id, op: 'end' })); });
|
||||||
|
// 客户端提前断开:让家里把上游请求也停掉,别白跑。
|
||||||
|
// 必须挂在 res 上:SSE 是 GET 无 body,req 的 'aborted' 只在传 body 时触发(且已废弃)。
|
||||||
|
// 漏掉这条时,前端关掉 SSE 后 client 会继续读流、继续往 WS 灌数据,切会话时
|
||||||
|
// 新旧两条流同时推,把单条 WS 占满,后发的 detail 请求只能排队。
|
||||||
|
res.on('close', () => {
|
||||||
|
if (!pending.has(id)) return; // 正常结束时 pending 已删
|
||||||
|
client.send(JSON.stringify({ id, op: 'abort' }));
|
||||||
|
pending.delete(id);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 主端口:按 Host 路由(有域名时的常规形态)
|
||||||
|
const server = http.createServer((req, res) => handleRequest(req, res, null));
|
||||||
|
|
||||||
|
// 固定端口:routes[{port, service}],一个端口钉死一个服务(没有域名也能多服务)
|
||||||
|
const extraServers = [];
|
||||||
|
for (const r of (CFG.routes || [])) {
|
||||||
|
const port = Number(r && r.port);
|
||||||
|
const service = String((r && r.service) || '').trim();
|
||||||
|
if (!port || !service) continue;
|
||||||
|
const s2 = http.createServer((req, res) => handleRequest(req, res, service));
|
||||||
|
s2.on('error', (e) => log('固定端口 ' + port + ' 起不来:' + e.message));
|
||||||
|
s2.listen(port, () => log('固定端口 ' + port + ' → 服务 "' + service + '"'));
|
||||||
|
extraServers.push(s2);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- client 回传的响应事件 ----------
|
||||||
|
function onClientMessage(raw) {
|
||||||
|
let m;
|
||||||
|
try { m = JSON.parse(raw); } catch (_) { return log('丢弃坏帧'); }
|
||||||
|
const entry = pending.get(m.id);
|
||||||
|
if (!entry) return; // 已超时/已断开,安静丢弃
|
||||||
|
const { res } = entry;
|
||||||
|
try {
|
||||||
|
if (m.ev === 'head') {
|
||||||
|
const h = {};
|
||||||
|
for (const [k, v] of Object.entries(m.headers || {})) {
|
||||||
|
const lk = k.toLowerCase();
|
||||||
|
// content-length 必然对不上(客户端已解压 / 分帧传输),交给 chunked
|
||||||
|
if (HOP_BY_HOP.has(lk) || lk === 'content-length') continue;
|
||||||
|
h[k] = v;
|
||||||
|
}
|
||||||
|
res.writeHead(m.status || 502, h);
|
||||||
|
} else if (m.ev === 'data') {
|
||||||
|
res.write(Buffer.from(m.b64 || '', 'base64'));
|
||||||
|
} else if (m.ev === 'end') {
|
||||||
|
res.end();
|
||||||
|
pending.delete(m.id);
|
||||||
|
} else if (m.ev === 'error') {
|
||||||
|
if (!res.headersSent) res.writeHead(502, { 'content-type': 'text/plain; charset=utf-8' });
|
||||||
|
res.end('tunnel error: ' + (m.msg || 'unknown'));
|
||||||
|
pending.delete(m.id);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
log('回写失败', m.id, e.message);
|
||||||
|
try { res.destroy(); } catch (_) {}
|
||||||
|
pending.delete(m.id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- WebSocket 升级:家里连上来 ----------
|
||||||
|
const wss = new WebSocketServer({ noServer: true });
|
||||||
|
|
||||||
|
server.on('upgrade', (req, socket, head) => {
|
||||||
|
const url = new URL(req.url, 'http://placeholder');
|
||||||
|
if (url.pathname !== '/tunnel') { socket.destroy(); return; }
|
||||||
|
if (url.searchParams.get('token') !== CFG.token) {
|
||||||
|
socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
|
||||||
|
socket.destroy();
|
||||||
|
return log('拒绝:token 不匹配', req.socket.remoteAddress);
|
||||||
|
}
|
||||||
|
wss.handleUpgrade(req, socket, head, (ws) => {
|
||||||
|
if (client && client.readyState === 1) {
|
||||||
|
log('新连接顶掉旧连接');
|
||||||
|
try { client.close(4000, 'replaced by new connection'); } catch (_) {}
|
||||||
|
}
|
||||||
|
client = ws;
|
||||||
|
ws.isAlive = true;
|
||||||
|
log('client 已连接', req.socket.remoteAddress);
|
||||||
|
ws.on('pong', () => { ws.isAlive = true; });
|
||||||
|
ws.on('message', onClientMessage);
|
||||||
|
ws.on('close', () => {
|
||||||
|
if (client === ws) client = null;
|
||||||
|
log('client 断开,未完成请求 ' + pending.size + ' 个一并收尾');
|
||||||
|
// 连接没了,等在途的请求不可能再有响应,直接 502,别让浏览器干等
|
||||||
|
for (const [id, e] of pending) {
|
||||||
|
try { if (!e.res.headersSent) e.res.writeHead(502); e.res.end('tunnel client disconnected'); } catch (_) {}
|
||||||
|
pending.delete(id);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
ws.on('error', (e) => log('client 错误', e.message));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// 心跳:跨境链路半死状态(TCP 还在但早不通了)靠这个发现
|
||||||
|
setInterval(() => {
|
||||||
|
if (!client || client.readyState !== 1) return;
|
||||||
|
if (client.isAlive === false) { log('心跳超时,踢掉 client'); try { client.terminate(); } catch (_) {} client = null; return; }
|
||||||
|
client.isAlive = false;
|
||||||
|
try { client.ping(); } catch (_) {}
|
||||||
|
}, CFG.heartbeatMs).unref();
|
||||||
|
|
||||||
|
// 在途请求超时兜底:SSE 长连接不该被砍,所以只在「还没收到 head」时计时
|
||||||
|
setInterval(() => {
|
||||||
|
const now = Date.now();
|
||||||
|
for (const [id, e] of pending) {
|
||||||
|
if (e.res.headersSent) continue;
|
||||||
|
if (!e.born) { e.born = now; continue; }
|
||||||
|
if (now - e.born > 120000) {
|
||||||
|
log('请求 120s 无响应,放弃', id);
|
||||||
|
try { e.res.writeHead(504); e.res.end('tunnel upstream timeout'); } catch (_) {}
|
||||||
|
pending.delete(id);
|
||||||
|
if (client && client.readyState === 1) client.send(JSON.stringify({ id, op: 'abort' }));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, 10000).unref();
|
||||||
|
|
||||||
|
function json(res, code, obj) {
|
||||||
|
const body = JSON.stringify(obj);
|
||||||
|
res.writeHead(code, { 'content-type': 'application/json; charset=utf-8', 'content-length': Buffer.byteLength(body) });
|
||||||
|
res.end(body);
|
||||||
|
}
|
||||||
|
|
||||||
|
// SSE / 长轮询不能被 Node 的默认超时砍掉
|
||||||
|
server.timeout = 0;
|
||||||
|
server.headersTimeout = 60000;
|
||||||
|
server.keepAliveTimeout = 65000;
|
||||||
|
|
||||||
|
server.listen(CFG.port, () => {
|
||||||
|
log('监听 0.0.0.0:' + CFG.port + ',健康检查 /__tunnel/health');
|
||||||
|
log('等待 client 连接 wss://<本机域名>/tunnel?token=***');
|
||||||
|
});
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "wxbot",
|
"name": "wxbot",
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"description": "wxbot.foresh.com: WeChat iLink bot console - QR login page + echo bot via @wechatbot/wechatbot",
|
"description": "WeChat iLink bot console - QR login page + echo bot via @wechatbot/wechatbot",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/server.js",
|
"main": "src/server.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|||||||
Reference in New Issue
Block a user