Compare commits
92
Commits
v2.5.0
...
111d6d6c90
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 | ||
|
|
0433e61941 | ||
|
|
7b1ef9a479 | ||
|
|
793be29331 | ||
|
|
b9fad470ee | ||
|
|
8168eae51e | ||
|
|
a2bedbf0d7 | ||
|
|
3d5c8a80f1 | ||
|
|
6eca2dd215 | ||
|
|
43dec0ad0f | ||
|
|
ecf32c0388 | ||
|
|
f2f8ba9b72 | ||
|
|
728b213821 | ||
|
|
14616e1606 | ||
|
|
cf43206c98 | ||
|
|
0922045a38 | ||
|
|
351662d18c | ||
|
|
4c4076ba13 | ||
|
|
65d05d2656 | ||
|
|
e50015cdc1 | ||
|
|
6d4b41ebfe | ||
|
|
a4897c1ace | ||
|
|
25f9e157ad | ||
|
|
8a92f2543d | ||
|
|
90158ab590 | ||
|
|
f587eb5b52 | ||
|
|
57ff5073d8 | ||
|
|
b657a22fe2 | ||
|
|
ffca861dc1 | ||
|
|
f6665e904e | ||
|
|
893fc92f6d | ||
|
|
b3a0d5370c | ||
|
|
8effba36dd | ||
|
|
77ef1ec11c | ||
|
|
0234bc85e5 | ||
|
|
24d7f023ba | ||
|
|
d03d8ba95b | ||
|
|
10bf2f554b | ||
|
|
0ec9aec93e | ||
|
|
5959b4a674 | ||
|
|
4e1c1f36d0 | ||
|
|
a52b227d8b | ||
|
|
317397154e | ||
|
|
0f9cc241bb | ||
|
|
69e44c27ae | ||
|
|
469e801319 | ||
|
|
5b45368f58 | ||
|
|
a7eecdbe97 | ||
|
|
c7394dc45f | ||
|
|
8764fedabc | ||
|
|
29e4f6e6ea | ||
|
|
59994b688a | ||
|
|
50c53fd885 | ||
|
|
870033f26d | ||
|
|
c892703673 | ||
|
|
01757d4f4b | ||
|
|
c0488938ff | ||
|
|
20824dc42e | ||
|
|
419e3fc914 | ||
|
|
83644c09e7 | ||
|
|
d06cd6cedf | ||
|
|
4e97194b04 | ||
|
|
8ef4ec1ee4 | ||
|
|
2d5467203b | ||
|
|
80e9dcb0aa | ||
|
|
b5cfa36832 | ||
|
|
f451027729 | ||
|
|
8a5c8b1547 |
@@ -7,6 +7,9 @@ data/
|
||||
tasks/
|
||||
skills/deps/
|
||||
skills/*/.deps_installed
|
||||
# 本地端(local/):运行期产物与生成的配置都不入库(含密钥,见 local/README.md)
|
||||
local/.runtime/
|
||||
local/config.local.yml
|
||||
# officecli 二进制资产:skills/office/install.sh 运行期拉取,不进 git
|
||||
skills/office/bin/
|
||||
skills/**/__pycache__/
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
| `wxbot/` | 微信 iLink 协议调制解调器(多实例) | 独立容器 `agent-wxbot` |
|
||||
| `mcp/` | 同栈 MCP 服务:`web_search` / `image_task` / `video_task` / `asr` | 四个容器,仅内网 |
|
||||
| `skills/` | 目录式技能(`SKILL.md` + `run.py`/`run.sh`) | 运行时挂载,`skills/deps` 为依赖层 |
|
||||
| `local/` | **本地端启动器**:同一份代码跑在本机(不起 Docker / executor),`start.sh` 负责探测、装依赖、守护 | 独立于 compose,见 `docs/local-mode.md` |
|
||||
| `scripts/` | `init.sh` 生成 `.env` + 首次创建 `config.yml`(仅初始管理员);`init_host.sh` 裸机初始化 | 幂等,**不覆盖已有配置** |
|
||||
| `docs/` | 专题文档:`tool-design.md`(工具接口规范)、`OFFICE.md` | — |
|
||||
| `tasks/` | **运行时数据**:每个会话一个工作目录 | gitignore |
|
||||
@@ -179,6 +180,10 @@ curl -s http://127.0.0.1:8090/api/health
|
||||
由 `server.js` 传函数进去。
|
||||
- 前端是**无构建的经典脚本**:新增文件要同时改 `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">`,
|
||||
漏了不报错、界面只是空白。
|
||||
|
||||
## 常见任务去哪改
|
||||
|
||||
|
||||
@@ -1,483 +1,77 @@
|
||||
# Agent 任务台
|
||||
|
||||
自托管的通用 Agent 系统。浏览器或微信发来任务,服务端调度模型、调用工具,在独立工作目录里生成文件并回传结果。
|
||||
自托管的 Agent 系统。浏览器或微信下发任务,模型在独立工作目录里读写文件、执行命令、调用技能,产物直接回传。
|
||||
|
||||
它不是聊天壳子:每个会话对应一个真实的 Linux 工作目录,模型可以读写文件、执行命令、抓网页、操作 SQLite、调用技能和 MCP 服务;命令在隔离容器中运行,文件可以直接下载或生成公网临时链接。
|
||||
|
||||
- 面向个人或小团队自用,单实例部署。
|
||||
- 模型层兼容任何 OpenAI `/chat/completions` 接口。
|
||||
- 前端是免构建的移动优先 H5,HTTPS 下可安装为 PWA。
|
||||
|
||||
---
|
||||
|
||||
## 能力
|
||||
|
||||
| 能力 | 说明 |
|
||||
|---|---|
|
||||
| 任务会话 | 每个会话一个独立目录 `tasks/<会话 id>/`,历史、文件、模型绑定都随会话保存 |
|
||||
| 模型池 | 多平台、每平台多 key、每平台多模型;key 共享并发,不独占、不排队 |
|
||||
| 工具调用 | 文件读写编辑、目录列举、复制、命令执行、网页抓取、SQLite、定时任务、技能、长期记忆等 14 个内置工具 |
|
||||
| 隔离执行 | `terminal` 和技能在 `agent-executor` 容器中运行,只看到当前会话目录,根文件系统只读 |
|
||||
| 大文件交付 | 文件面板上传/下载/打包 zip;外部服务取图走带过期时间的公网短链 |
|
||||
| 上下文管理 | 手动压缩、按 token 阈值提示压缩、历史重放自动裁剪、会话标题自动生成 |
|
||||
| 回合中投递 | 运行中发的消息先进输入框上方的待发送条幅:默认等本轮结束自动发出;可「干预」(当前工具跑完就插话)或「立即发送」(终止本轮并立刻发)。队列在服务端,关页面不丢 |
|
||||
| 定时任务 | 每会话最多一个 cron 任务;触发前清空模型可见历史,按计划执行并推送结果 |
|
||||
| 微信接入 | 扫码绑定个人微信,文本/图片/视频/文件进入同一套会话与命令体系 |
|
||||
| 语音输入 | 输入框为空时发送键变麦克风:点一下进入语音模式,输入框位置变成「按住 说话」,松开即转写并直接发送;发送键位置变键盘按钮可切回打字。套壳 App 走原生录音(http 页面也能用),浏览器走 MediaRecorder(需 HTTPS);识别在 `mcp_asr`,不经过模型、不消耗 token |
|
||||
| 长期记忆 | 会话收口时生成第一人称工作日记;微信新会话注入最近几条,`recall` 可检索全部 |
|
||||
| 用户画像 | 记录称谓、行业、偏好,会话创建时冻结注入,跨会话生效 |
|
||||
| 技能 | 目录式技能(`SKILL.md` + `run.py`/`run.sh`),可在设置页管理 |
|
||||
| MCP | 启动时发现 MCP 服务的工具;仓库内自带 `web_search` / `image_task` / `video_task` 三个 |
|
||||
| 多用户 | 登录账号、管理员角色、按用户隔离的会话列表与画像 |
|
||||
|
||||
---
|
||||

|
||||
|
||||
## 快速开始
|
||||
|
||||
### 前置条件
|
||||
### 服务器
|
||||
|
||||
- Linux 服务器,Docker 与 Docker Compose v2。
|
||||
- 至少一个 OpenAI 兼容模型平台的 API Key。
|
||||
- 一个可用端口,默认 `8090`。
|
||||
|
||||
Debian 12 裸机可以先跑 `scripts/init_host.sh`(幂等,可重复执行,也可单独拷到服务器上跑):它会配好 Swap、Docker、国内镜像加速与基础 shell 环境;`REGION=oversea` 切海外源。跑完会打印后续的 `init.sh` 与部署步骤。
|
||||
|
||||
### 1. 初始化(只做部署接线)
|
||||
|
||||
在仓库根目录执行:
|
||||
需要 Docker 与 Compose v2:
|
||||
|
||||
```bash
|
||||
./scripts/init.sh
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
它只做三件事,**幂等**,随便重跑:
|
||||
打开 `http://<服务器 IP>:8090`,用 `admin` / `admin` 登录,先改密码,再到「设置 → 模型」添加平台和 API Key,保存后点「重启服务」。
|
||||
|
||||
1. 生成 `.env` 里的 `EXECUTOR_TOKEN` / `WXBOT_TOKEN` / `AUTH_SECRET`(已有值原样复用,重跑不会掉登录态,也不会换掉 executor 的 token)。
|
||||
2. 探测公网 IP 并写成 `PUBLIC_BASE_URL`(外部服务靠它回取会话文件,图生视频需要)。知道地址就直接给:
|
||||
```bash
|
||||
PUBLIC_IP=1.2.3.4 ./scripts/init.sh
|
||||
```
|
||||
3. 确保 `config.yml` 存在:**不存在时**才创建,内容只有初始管理员 `admin` / `admin`。已有文件**绝不改写**。
|
||||
### 本机运行
|
||||
|
||||
脚本不再生成模型平台 / MCP / 语音这些配置——它们全部在前端「设置」里完成,写的就是同一个 `config.yml`。所以重跑脚本永远不会清掉你配好的东西(旧版脚本会覆盖,这是本次的行为变化)。
|
||||
|
||||
- 想换初始管理员:仅在**首次创建**时生效,`AUTH_USER=me AUTH_PASSWORD='强密码' ./scripts/init.sh`。
|
||||
- `config.yml` 被 Docker 误建成了空目录(源文件缺失时才会这样):脚本会自动删掉并重建;目录非空则报错让你手工处理。
|
||||
|
||||
没有 `config.yml` 也能启动:`platforms` 为空、`auth` 为空即“无模型 + 不启用登录”,登录后从设置页补齐即可(保存后点「重启服务」生效)。
|
||||
|
||||
### 2. 启动
|
||||
macOS / Linux,Node 20+,不需要 Docker:
|
||||
|
||||
```bash
|
||||
# 迁移:把旧版根目录的 config.yml 原样留着即可,init.sh 不会动它
|
||||
docker compose up -d --build
|
||||
docker compose logs -f agent-core
|
||||
./local/start.sh # 后台启动
|
||||
./local/stop.sh
|
||||
```
|
||||
|
||||
看到 `Agent server listening on 8090` 即启动完成。
|
||||
首次运行会让你选一个工作目录(技能、会话、数据库都在里面)。命令直接在本机执行,没有沙箱隔离,只监听 `127.0.0.1`。
|
||||
|
||||
首次启动还会运行一次性的 `agent-executor-init`,把技能依赖安装到 `./skills/deps`,随后自动退出,属正常现象。
|
||||
## 组成
|
||||
|
||||
### 3. 访问与首次配置
|
||||
|
||||
浏览器打开:
|
||||
|
||||
```text
|
||||
http://<服务器 IP>:<AGENT_PORT>
|
||||
```
|
||||
|
||||
首次用 `admin` / `admin` 登录(**登录后立刻在「设置 → 账户」改密码**)。默认端口 `8090`,可用 `.env` 的 `AGENT_PORT` 修改。
|
||||
|
||||
登录后去「设置」补齐三块,保存后点页面顶部的「重启服务」:
|
||||
|
||||
| 设置页 | 配什么 |
|
||||
| 目录 | 说明 |
|
||||
|---|---|
|
||||
| 模型 | 平台地址 + API Key + 模型 id(`extra_params` / `thinking_params` / profile 等在「高级」里) |
|
||||
| MCP | `image_task` / `video_task` / `asr` 需上游 key;`web_search` 免费,地址 `http://mcp_web_search:3000/` |
|
||||
| 用户 | 其余账号、角色、默认模型;改密码在「账户」 |
|
||||
|
||||
对外只需要放行 core 这一个端口。`agent-executor`、`wxbot` 和 MCP 服务都只在 Docker 内网,不映射到宿主机。
|
||||
|
||||
### 4. 同栈 MCP 服务
|
||||
|
||||
初始 `config.yml` 不包含任何 MCP 服务。设置页「MCP」会把四个同栈服务作为**内置服务卡片**列出来,
|
||||
点卡片 → 填表 → 保存即可(url 与 header 名由 `app/server/presets.json` 提供,不用记)。
|
||||
`web_search` 免费、无需 key;另外三个要填上游 key。手工写 YAML 的形状如下(容器不存密钥):
|
||||
|
||||
```yaml
|
||||
mcp_servers:
|
||||
- name: web_search
|
||||
url: "http://mcp_web_search:3000/"
|
||||
|
||||
# - name: image_task
|
||||
# url: "http://mcp_image_task:3000/mcp"
|
||||
# headers:
|
||||
# Authorization: Bearer <upstream-api-key>
|
||||
# X-Image-Task-Base-Url: "https://open.bigmodel.cn/api/paas/v4" # 任意 OpenAI 兼容的 images 上游(生成 /images/generations、编辑 /images/edits)
|
||||
# X-Image-Task-Model: "CogView-4"
|
||||
# mode: skill
|
||||
# - name: video_task
|
||||
# url: "http://mcp_video_task:3000/mcp"
|
||||
# headers:
|
||||
# Authorization: Bearer <zhipu-api-key>
|
||||
# mode: skill
|
||||
# - name: asr
|
||||
# url: "http://mcp_asr:3000/mcp"
|
||||
# headers:
|
||||
# Authorization: Bearer <key> # 免鉴权的自建服务可省
|
||||
# X-ASR-Base-Url: "https://<host>/v1"
|
||||
# X-ASR-Model: "whisper-1"
|
||||
# mode: skill
|
||||
```
|
||||
|
||||
`web_search` / `image_task` / `video_task` / `asr` 四个容器与 core 由同一个根 `docker-compose.yml` 启动(与是否写进配置无关),没有先后顺序,也不占宿主机端口。工具说明、header 覆盖项与调试方式见 [mcp/README.md](mcp/README.md)。
|
||||
|
||||
`ASR_URL`(`docker-compose.yml` 里固定为 `http://mcp_asr:3000`)是 core 调用语音转写的基地址;把 `mcp_asr` 放到另一台机器时改这一行即可(那台要能接受 `Authorization` / `X-ASR-Base-Url` / `X-ASR-Model` 三个 header)。
|
||||
|
||||
语音输入(H5 输入框里说话)走的是另一条路:客户端录音 → `POST /api/asr/transcribe` → `mcp_asr` 的 `/transcribe`,**不经过模型、不消耗 token**,结果插入输入框可编辑。客户端录音契约(Android 套壳原生桥 / 浏览器 MediaRecorder)见 [docs/voice-input.md](docs/voice-input.md);删掉 `config.yml` 里的 `asr` 段即整体关闭。
|
||||
|
||||
`mcp_asr` 自己**不存任何平台密钥**:上游 key / base_url / model 都由 core 从这里那段 `asr.headers` 随请求带进去,换平台只改 YAML(不用重建镜像、不用动 `.env`),也不预设任何厂商。
|
||||
|
||||
接入栈外的 MCP 服务:在设置页添加 `url` / `headers`,或在 `config.yml` 的 `mcp_servers` 追加一项。服务不可达时 core 只在启动日志里告警,不影响 Web 主流程,但对应工具不会下发给模型。
|
||||
|
||||
每个服务可用 `mode` 控制「工具是否下发给模型」:
|
||||
|
||||
| `mode` | 连接/发现 | 进 tools 数组 | 进技能清单 | 谁可以调用 |
|
||||
|---|---|---|---|---|
|
||||
| `advertise`(默认) | ✓ | ✓ | ✗ | 模型与技能 |
|
||||
| `skill` | ✓ | ✗ | ✓ | `skill` 工具与 `lab` |
|
||||
| `disable` | ✗ | ✗ | ✗ | 无人 |
|
||||
|
||||
`skill` 用于「能力包在技能后面」的场景:工具照常发现并注册,只是不进模型的 tools 数组,改为以技能形式暴露——`{"op":"list"}` 能看到它,`{"op":"get","name":"<名>"}` 直接返回 MCP 原始的 `description` + `input_schema`,`{"op":"run","name":"<名>","args":{…}}` 转发给服务。不用在 `skills/` 里建目录。旧字段 `enable` 已废弃,`mode: silent` 已移除(启动会报错并提示改用 `skill`)。
|
||||
|
||||
工具发现只在启动时做一次,因此发现失败后会自动按 **2s / 20s / 1min 重试 3 次**(覆盖 compose 并行拉起与宿主机重启后的容器乱序);成功后工具在下一轮请求即可用,三次都失败则需重启 core。四个 MCP 服务都配了 `/health` 健康检查,`docker ps` 可直接看状态。
|
||||
|
||||
---
|
||||
|
||||
## 使用
|
||||
|
||||
### 会话与模型
|
||||
|
||||
- 新建会话时自动绑定一个模型;不选则按平台轮转选择。
|
||||
- 会话创建后模型绑定保持,重启、追问都不会丢。
|
||||
- 模型被删除或禁用后,下一条消息会自动改选原平台的可用模型。
|
||||
- 管理员可在「设置 → 用户」给某个用户锁定默认模型。
|
||||
- 顶部「切换模型」只在该会话空闲时可用;正在输出时会拒绝换绑。
|
||||
|
||||
会话状态:
|
||||
|
||||
| 状态 | 含义 |
|
||||
|---|---|
|
||||
| 保持中 | 回合已结束,可以直接继续追问 |
|
||||
| 活跃中 | 正在执行模型回合 |
|
||||
| 已完成 | 已手动断开或空闲超时收口,仍可继续发消息 |
|
||||
| 已终止 | 用户主动停止 |
|
||||
|
||||
### 文件
|
||||
|
||||
- 输入框附件、微信附件都落在 `tasks/<会话 id>/`。
|
||||
- 右侧「任务文件」面板支持上传、下载、批量打包、删除、子目录浏览。
|
||||
- 模型生成的文件与用户上传的文件在同一目录,AI 可直接继续处理。
|
||||
- 超过 50 MB 的单文件上传会被拒绝;移动端大图上传前会在浏览器端压缩。
|
||||
|
||||
### 上下文压缩
|
||||
|
||||
- 顶部「压缩」可手动触发:模型基于完整历史生成摘要,摘要之前的消息标记为已存档,UI 仍可见,但不再发给模型。
|
||||
- 当单回合输入 token 超过 `agent.auto_compress_tokens` 时,前端会弹一次确认框,询问是否压缩。
|
||||
- 历史重放还会自动把较旧的 `write_file` 参数正文、`fetch` / `read_file` 回执替换为单行占位,数据库与 UI 不受影响。
|
||||
|
||||
### 定时任务
|
||||
|
||||
对 AI 说「每天早上九点汇总……」,它会在当前会话创建 cron 任务:
|
||||
|
||||
- 每会话最多一个任务,最小间隔 1 小时,时区固定 `Asia/Shanghai`。
|
||||
- 每次触发前,会话历史整体标记为已存档,模型只看到任务提示词,等价一次全新会话。
|
||||
- 执行结果留在会话里,同时可通过微信推送。
|
||||
- 创建任务后,当前会话会收口为该任务的「专柜」,用户下一条消息自动进入新会话。
|
||||
|
||||
### 微信
|
||||
|
||||
在「设置 → 账户 → 微信绑定」生成二维码,扫码后即可单线对话:
|
||||
|
||||
- 微信消息复用同一套会话和命令层,支持 `/new`、`/list`、`/switch`、`/delete`、`/rename`、`/models`、`/think`、`/stop`、`/compact`、`/clear`、`/status`、`/help`。
|
||||
- 回合进行中发消息=自动干预:当前工具调用跑完就插话(同批剩余调用标记为「因你介入未执行」),不会等本轮结束,也不会打断正在执行的命令。要立刻中止用 `/stop`。
|
||||
- 图片、视频、文件会落到当前会话目录;单发媒体只留痕,不唤醒 AI。
|
||||
- AI 最终回复会推回微信;较长回复自动分段,超长时落成 `.md` 文件卡片。
|
||||
- 定时任务完成或失败也会通知微信。
|
||||
|
||||
### 长期记忆
|
||||
|
||||
- 会话空闲超过 `memory.wrap_idle_ms`(默认 4 小时)后,后台生成一条工作日记碎片,并归档、解绑通道。
|
||||
- 微信新会话开场注入最近 `memory.inject_max` 条碎片。
|
||||
- AI 可用 `recall` 工具按关键词、日期索引、具体某天检索全部日记。
|
||||
- 删除会话会连带删除它的日记碎片;清空会话在普通情况下也会删除,但定时任务「专柜」例外。
|
||||
- 日记调试页:`/memory.html`。
|
||||
|
||||
---
|
||||
| [`app/`](app/README.md) | agent-core:Express + SQLite + 前端静态资源,唯一对外端口 |
|
||||
| `executor/` | agent-executor:隔离的命令执行、Office 预览网关 |
|
||||
| [`wxbot/`](wxbot/README.md) | 微信接入 |
|
||||
| [`mcp/`](mcp/README.md) | 四个 MCP 服务:网页搜索、图片生成、视频生成、语音转写 |
|
||||
| [`skills/`](skills/README.md) | 内置技能 |
|
||||
| [`local/`](local/README.md) | 本机模式启动器 |
|
||||
|
||||
## 配置
|
||||
|
||||
`config.yml` 只给 `agent-core` 读取,包含平台密钥和登录密钥。`agent-executor`、`wxbot` 不挂载、不读取它。
|
||||
|
||||
主要配置段:
|
||||
|
||||
| 段 | 作用 |
|
||||
|---|---|
|
||||
| `platforms` | 模型平台池:`name`、`url`、`type`、`models`、`keys` |
|
||||
| `model_profiles` | prompt + 工具名单组合;模型用 `profile: <名>` 引用 |
|
||||
| `tools_deny` | 全局工具黑名单,默认屏蔽元工具 `lab` |
|
||||
| `auth` | 登录账号、`secret`、有效期;留空则不启用认证 |
|
||||
| `mcp_servers` | 外部 MCP 服务:`url`、`headers`、`mode`(advertise / skill / disable)、`timeout_ms`、工具名单 |
|
||||
| `public_link` | 公网临时链接前缀与有效期 |
|
||||
| `agent` | 温度、最大工具迭代、重试、语言、压缩阈值、空闲收口、历史裁剪 |
|
||||
| `memory` | 日记注入条数、保留期、空闲收口阈值 |
|
||||
| `terminal` / `fetch` | 命令超时与输出上限、抓取超时、字节数、SSRF 开关 |
|
||||
| `skills` | 技能目录与单次执行超时 |
|
||||
| `upload` | 前端大图压缩阈值与参数 |
|
||||
| `workspace_root` / `data_root` | 任务目录与 SQLite / 调试产物目录 |
|
||||
|
||||
平台结构示例:
|
||||
`./scripts/init.sh` 首次生成 `config.yml`,只有 agent-core 读取。日常改动走设置页,保存后点「重启服务」。
|
||||
|
||||
```yaml
|
||||
platforms:
|
||||
- name: bigmodel
|
||||
url: https://open.bigmodel.cn/api/paas/v4
|
||||
type: bigmodel # 决定余额查询适配器
|
||||
models:
|
||||
- id: glm-5.3-flash
|
||||
vision: true
|
||||
extra_params: { reasoning_effort: "low", tool_stream: true }
|
||||
thinking_params: { reasoning_effort: "max" }
|
||||
keys:
|
||||
- api_key: "sk-..."
|
||||
```
|
||||
|
||||
通用模型字段:
|
||||
端口与其余环境变量在 `docker-compose.yml` 里。
|
||||
|
||||
- `enable: false`:模型不进池,不参与分配。
|
||||
- `vision: false`:读图时不回传像素,回执只给结构化说明(`reason: no_vision`)。
|
||||
- `profile: <名>`:引用 `model_profiles`,不配则使用默认全量 prompt 与工具。
|
||||
- `reasoning_ack_field`:需要把思考链回传给上游时填写,例如 DeepSeek 系的 `reasoning_content`。
|
||||
|
||||
日常修改配置建议使用设置页;改完需重启生效。设置页写入前会先校验,非法配置不会覆盖原文件。
|
||||
|
||||
### 环境变量
|
||||
|
||||
| 变量 | 作用 |
|
||||
|---|---|
|
||||
| `AGENT_CONFIG` | core 配置文件路径,容器内固定 `/app/config.yml` |
|
||||
| `PORT` | core 监听端口,容器内 `8090` |
|
||||
| `EXECUTOR_URL` | `agent-executor` 地址;空则命令在 core 进程内本地执行,仅适合开发 |
|
||||
| `EXECUTOR_TOKEN` | core ↔ executor 的 Bearer token,两侧同值 |
|
||||
| `ASR_URL` | core 拼接 `/transcribe` 的基地址,compose 里固定 `http://mcp_asr:3000`(把 `mcp_asr` 放别处时改那一行) |
|
||||
| `ASR_LOG_LEVEL` | `mcp_asr` 日志等级 |
|
||||
| `WXBOT_URL` | wxbot 地址;置空则微信功能整体关闭 |
|
||||
| `WXBOT_TOKEN` | core ↔ wxbot 的共享 token |
|
||||
| `PUBLIC_BASE_URL` | 对外的完整地址(如 `http://1.2.3.4:8090`),作为 `public_link` 的默认值;设置页填过则以设置页为准 |
|
||||
| `PREVIEW_PROXIES` | 覆盖内置预览反代注册表(JSON 数组) |
|
||||
| `EXECUTOR_LOG_LEVEL` / `WXBOT_LOG_LEVEL` | 两个附属服务的日志等级 |
|
||||
|
||||
`config.yml` 与 `.env` 都含密钥,已在 `.gitignore` 中。不要提交,也不要挂给不需要它的容器。
|
||||
|
||||
---
|
||||
|
||||
## 内置工具
|
||||
|
||||
模型实际收到的工具是内置工具加 MCP 工具,再经 `tools_deny` 与模型 `profile` 过滤。
|
||||
|
||||
| 工具 | 用途 |
|
||||
|---|---|
|
||||
| `read_file` | 读文本或图片;大文件返回符号大纲;支持 `@<会话 id>/<路径>` 只读查看历史会话文件 |
|
||||
| `write_file` | 新建或覆盖文本文件 |
|
||||
| `edit_file` | 按 `old_text` / `new_text` 做精确或容错编辑 |
|
||||
| `list_directory` | 单层列目录;支持 `@<会话 id>/<路径>` |
|
||||
| `copy_path` | 复制文件或目录;可从历史会话导入文件 |
|
||||
| `terminal` | 执行 shell 命令;默认在会话目录,超时可终止 |
|
||||
| `fetch` | 抓取 HTTP/HTTPS 并转 Markdown;带 SSRF 防护与分段续读 |
|
||||
| `mint_public_link` | 为会话内文件签发短期公网链接 |
|
||||
| `skill` | 技能:`op` = `list` / `get` / `run`;`name` 指技能,`args` 传参数 |
|
||||
| `db` | 操作会话本地 `data.db`:`exec`、`query`、`insert`、`tables`、`schema` |
|
||||
| `schedule` | 定时任务 `get` / `list` / `create` / `update` / `delete` |
|
||||
| `profile` | 用户画像 `list` / `set` / `add` / `remove` |
|
||||
| `recall` | 长期记忆 `search` / `days` / `day` |
|
||||
| `lab` | 元工具:按名字调用任意工具,`help` 可列出全部工具;默认被全局黑名单屏蔽 |
|
||||
|
||||
跨会话路径只读:`@` 形式只用于 `read_file`、`list_directory` 和 `copy_path` 的源路径,且只能访问同一用户自己的会话。要真正处理旧文件,先用 `copy_path` 导入当前会话。
|
||||
|
||||
---
|
||||
|
||||
## 技能
|
||||
|
||||
技能是 `skills/<名字>/` 目录:
|
||||
|
||||
```text
|
||||
skills/my-skill/
|
||||
├── SKILL.md # 必需:描述、input_schema、可选 required / visit_url
|
||||
├── run.py | run.sh # 入口,唯一命令行参数是 JSON 字符串
|
||||
├── requirements.txt # 可选:Python 依赖
|
||||
└── install.sh # 可选:系统层安装脚本,镜像构建期执行
|
||||
```
|
||||
|
||||
- `SKILL.md` 的 `description` 会进入 system prompt,模型启动时就知道有哪些技能。
|
||||
- `input_schema.required` 在 `op=run` 前校验。
|
||||
- MCP 工具不用建目录:给该服务配 `mode: skill`,平台会自动把它暴露成技能(`get` 返回 MCP 原始的
|
||||
`input_schema`,`run` 转发),见上文「同栈 MCP 服务」。
|
||||
- 入口脚本以绝对路径启动;远端执行时 cwd 是会话目录,本地开发时是技能目录。相对路径参数会先按会话目录转成绝对路径。
|
||||
- `requirements.txt` 的依赖由 `agent-executor-init` 安装到 `skills/deps`;技能容器通过 `PYTHONPATH` 可见。
|
||||
- `install.sh` 在镜像构建期以 root 执行,用于必须落在系统层的依赖。改完需要重建 executor 镜像。
|
||||
- 技能目录在 executor 中只读,运行期不能修改技能本身。
|
||||
|
||||
设置页支持创建、重命名、删除技能和在线编辑文本文件;技能列表变更后会实时刷新 system prompt 中的清单,无需重启。
|
||||
|
||||
---
|
||||
|
||||
## 安全模型
|
||||
|
||||
### 部署边界
|
||||
|
||||
- 对外只暴露 `agent-core` 端口。
|
||||
- `agent-executor` 使用独立的 mount / PID / IPC namespace,只 bind 当前会话目录;根文件系统只读,丢弃全部 capability 后仅保留 `SYS_ADMIN`。
|
||||
- 命令容器没有独立网络 namespace,所以 executor 会拒绝来自自身容器网卡的 `/exec` 请求,避免 token 泄漏后被借用。
|
||||
- `wxbot` 只挂内网;微信登录凭证在 `./wxbot/data`,等同微信账号权限,不要外泄。
|
||||
- 配置文件、`.env`、微信凭证、任务目录、SQLite 都属于敏感数据。
|
||||
|
||||
### 认证与授权
|
||||
|
||||
- 登录使用 HMAC 签名的 HttpOnly Cookie,支持 `Authorization: Basic` 作为脚本 / curl 的兜底。
|
||||
- `auth.users` 留空则完全关闭认证,只适合本机或完全可信网络。
|
||||
- 管理员接口:配置读写、用户管理、进程重启。
|
||||
- 删除用户会连带清理其微信绑定(含 wxbot 实例与凭证)、会话(含任务目录)、画像、长期记忆与通道绑定;`model_usage` 的用量统计保留(与删会话一致,不清账)。
|
||||
- **重要**:系统按单租户设计。除上述管理员接口外,会话、消息、文件、技能等 API 只校验「已登录」,不按用户做资源级授权;按用户的会话列表隔离发生在前端查询层。不要把实例开放给互不信任的用户。
|
||||
|
||||
### 公网临时链接
|
||||
|
||||
`mint_public_link` 生成 22 字符随机 ID,链接形如:
|
||||
|
||||
```text
|
||||
http://<host>/p/<id>
|
||||
```
|
||||
|
||||
- 只由 core 进程内的工具签发,签发前校验文件在任务目录内且 `realpath` 未越界。
|
||||
- 默认 30 分钟过期,可配置 1 分钟到 24 小时。
|
||||
- 链接可重复使用,直到过期;服务重启后全部失效。
|
||||
- 响应头按类型分开:图片(`png/jpg/webp/gif/bmp/tif/avif/ico/svg`)返回 `inline` + 对应 `image/*`,点开链接直接看图;其余类型返回 `attachment`,交给浏览器/WebView 下载(SVG 额外带 `Content-Security-Policy: sandbox`,禁止内嵌脚本)。
|
||||
- 任何人拿到链接即可匿名访问,不要对含密钥的文件签发。
|
||||
|
||||
### HTTPS
|
||||
|
||||
仓库不内置 TLS 反向代理。直接 `http://IP:端口` 使用时:
|
||||
|
||||
- PWA / Service Worker 不会注册。
|
||||
- 复制按钮会回退到旧 API。
|
||||
- 登录 Cookie 不带 `Secure` 标志,HTTP 下正常工作。
|
||||
|
||||
如果前面加 nginx 等反向代理,SSE 必须关闭缓冲:
|
||||
|
||||
```nginx
|
||||
proxy_http_version 1.1;
|
||||
proxy_buffering off;
|
||||
proxy_read_timeout 3600s;
|
||||
```
|
||||
|
||||
公网链接前缀取 `config.yml` 的 `public_link.base_url`(设置页「服务 → 公网地址」);没填时用 `.env` 的 `PUBLIC_BASE_URL`(`init.sh` 会自动探测写入)。前置了反向代理 + HTTPS 的部署,直接把它填成域名即可。
|
||||
|
||||
---
|
||||
|
||||
## 运维
|
||||
|
||||
### 数据位置
|
||||
|
||||
| 宿主机路径 | 容器内 | 内容 |
|
||||
|---|---|---|
|
||||
| `./tasks/` | `/workspace/tasks` | 每个会话的工作目录 |
|
||||
| `./data/` | `/workspace/data` | SQLite `.agent.db`、`prompt.txt` 调试产物 |
|
||||
| `./skills/` | `/workspace/skills` | 技能与共享依赖 |
|
||||
| `./config.yml` | `/app/config.yml` | core 配置 |
|
||||
| `./wxbot/data/` | `/data` | 微信登录凭证 |
|
||||
|
||||
备份至少覆盖 `data/`、`tasks/`、`config.yml`;需要保留微信登录态时再备份 `wxbot/data/`。
|
||||
|
||||
### 升级
|
||||
## 升级
|
||||
|
||||
```bash
|
||||
git pull
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
数据库与任务目录都在 bind mount 中,升级不丢数据。进程重启时,执行中的回合会被打断;`active` 会话会归位为保持中,用户再发消息即可继续。
|
||||
数据在 `data/`、`tasks/` 和 `config.yml` 里,升级不受影响。
|
||||
|
||||
> 从旧的「agent + mcp 双仓库」部署升级:旧 mcp 容器占着 `agent-mcp-net` 和同名 `container_name`,需先停旧栈再 `up` 本栈,否则会报 `network agent-mcp-net has active endpoints` 或 `container name ... is already in use`。旧仓库的 `down` 只需执行一次:
|
||||
>
|
||||
> ```bash
|
||||
> cd /root/workspace/tools/mcp && docker compose down
|
||||
> cd /root/workspace/tools/agent && docker compose up -d --build
|
||||
> ```
|
||||
>
|
||||
> 微信服务已改名为 `agent-wxbot`(原容器名 `wxbot`)。旧容器不受新 compose 管理,升级后需手动清理,否则两个实例会同时轮询同一个微信号:`docker rm -f wxbot`。
|
||||
## 安全
|
||||
|
||||
### 日志与健康检查
|
||||
- 对外只开 agent-core 一个端口,其余服务只在 Docker 内网
|
||||
- 命令在 executor 容器里执行,只挂当前会话目录,根文件系统只读
|
||||
- 单租户设计:除管理员接口外不做用户级资源隔离,不要开放给互不信任的人
|
||||
- `config.yml`、`.env`、`wxbot/data/` 存密钥,已加入 `.gitignore`
|
||||
|
||||
```bash
|
||||
docker compose logs -f agent-core
|
||||
docker compose logs -f agent-executor
|
||||
docker compose logs -f agent-wxbot
|
||||
curl -s http://127.0.0.1:8090/api/health
|
||||
# {"ok":true,"service":"agent-core","api":1,"time":...,"auth_required":true}
|
||||
```
|
||||
## License
|
||||
|
||||
- `GET /api/health` 是**唯一免登录接口**,供运维探活,也供套壳 App 校验用户手填的服务器地址。
|
||||
客户端判定条件:HTTP 200 且 `ok === true` 且 `service === 'agent-core'`——**不要只看状态码**,
|
||||
填错到别的站点或反代首页同样可能回 200。地址末尾的 `/` 可带可不带。
|
||||
`auth_required` 用于区分「地址对了但没登录」与「地址错了」。
|
||||
|
||||
- core 日志等级由 `config.yml` 的 `log_level` 控制,改完重启生效。
|
||||
- executor / wxbot 的日志等级由各自环境变量控制,`debug` 会打印完整交互。
|
||||
- 启动时会在 `data/prompt.txt` 写入实际下发的 system prompt 与各 profile 的工具清单,便于核对。
|
||||
|
||||
### 常见问题
|
||||
|
||||
| 现象 | 原因 / 处理 |
|
||||
|---|---|
|
||||
| 启动时报 `network agent-mcp-net has active endpoints` | 旧的双仓库部署残留:先停旧的 mcp 仓库(`docker compose down`),再 `up` 本栈 |
|
||||
| 套壳 App 填了服务器地址仍连不上 | 先 `curl <地址>/api/health` 看是否返回 `service:agent-core`;再查 Android 9+ 默认禁止明文 HTTP(需 `usesCleartextTraffic`)与 https 自签证书 |
|
||||
| 麦克风按钮不显示 | `config.yml` 的 `mcp_servers` 里没有启用的 `asr` 段 / 该段缺 `X-ASR-Base-Url`(`GET /api/asr/status` 会返回 `reason`);或浏览器以 `http://<IP>` 访问且没有原生录音桥(非安全上下文开不了麦,见 `docs/voice-input.md`) |
|
||||
| 点麦克风提示「语音识别服务不可用」 | `mcp_asr` 未起来(`docker compose logs --tail=50 mcp_asr`);或 `config.yml` 的 `asr.headers` 缺 `X-ASR-Base-Url` / `X-ASR-Model` |
|
||||
| `config.yml` 变成目录 | 启动前文件不存在,Docker 自动建了同名目录;重跑 `./scripts/init.sh` 会自动删除空目录并重建(非空目录需先备份再手工删除) |
|
||||
| 没有可用模型 | `platforms` 为空或模型全部禁用;在设置页添加后重启 |
|
||||
| 创建会话报「无可用模型」 | 模型池为空,或指定模型所在平台没有 key |
|
||||
| 技能依赖缺失 | 重新 `docker compose up -d --build agent-executor`;或检查 `skills/deps` |
|
||||
| 微信设置页显示未连接 | wxbot 未启动,或 `WXBOT_TOKEN` 两侧不一致 |
|
||||
| 图生视频拉不到参考图 | `public_link.base_url` 未配置,或公网不可达 |
|
||||
| 启动日志出现 `xxx 工具发现失败` | 当时服务未就绪,core 会按 2s/20s/1min 重试 3 次;仍失败则重启 `agent-core` |
|
||||
|
||||
---
|
||||
|
||||
## 目录
|
||||
|
||||
```text
|
||||
agent/
|
||||
├── app/ agent-core:Express + SQLite + 前端静态资源
|
||||
├── executor/ agent-executor:隔离命令执行与 Office 预览网关
|
||||
├── wxbot/ 微信 iLink 协议调制解调器
|
||||
├── mcp/ 同栈 MCP 服务:web_search / image_task / video_task
|
||||
├── skills/ 技能目录
|
||||
├── tasks/ 会话工作目录(运行时生成)
|
||||
├── data/ SQLite 与调试产物(运行时生成)
|
||||
├── docs/ 专题文档
|
||||
├── docker-compose.yml
|
||||
└── scripts/init.sh
|
||||
```
|
||||
|
||||
进一步阅读:
|
||||
|
||||
- [mcp/README.md](mcp/README.md):同栈 MCP 服务(搜索 / 生图 / 生视频)。
|
||||
- [docs/OFFICE.md](docs/OFFICE.md):Office 文档技能与预览链路。
|
||||
- [docs/tool-design.md](docs/tool-design.md):工具接口设计规范。
|
||||
|
||||
## 开发
|
||||
|
||||
```bash
|
||||
cd app
|
||||
npm install
|
||||
node server/server.js
|
||||
```
|
||||
AGPL-3.0,见 [LICENSE](LICENSE)。
|
||||
|
||||
+17
-6
@@ -62,7 +62,7 @@ AGENT_CONFIG=./config.yml node server/server.js
|
||||
| `server/log.js` | 分级日志 `log.debug/info/warn/error(category, ...)` |
|
||||
| `server/balance.js` | 平台余额查询适配器(按 `platform.type` 分发) |
|
||||
| `server/version.js` | git commit/date:优先读 `version.json`(post-commit 钩子生成),宿主机有 git 时兜底 `git rev-parse`;页面版本号另外由 `routes/system.js` 的 `VERSION` 字面量决定 |
|
||||
| `server/templates/` | system prompt 模板、压缩/标题指令、profile prompt |
|
||||
| `server/templates/` | system prompt 模板、环境段(按部署形态二选一)、压缩/标题指令、profile prompt |
|
||||
|
||||
## 一次用户消息的生命周期
|
||||
|
||||
@@ -162,7 +162,7 @@ IM 用户在实时对话,回合中插话应当“当前这步跑完就插”
|
||||
|
||||
`buildMessages(session, language, mintUrl, profile)` 的输出顺序固定:
|
||||
|
||||
1. `system`:模板(`profile-default.txt` 或 profile 自定义 prompt)+ 技能清单段 + 语言指令;
|
||||
1. `system`:模板(`profile-default.txt` 或 profile 自定义 prompt)+ 环境段 + 技能清单段 + 语言指令;
|
||||
进程内按 `(profile, language)` 缓存,保证前缀缓存稳定。
|
||||
2. 画像快照(`sessions.profile_snapshot`,建会话/清空时冻结):作为首条 `user`。**不在 messages 表里**,
|
||||
压缩与归档碰不到它。
|
||||
@@ -223,10 +223,17 @@ IM 用户在实时对话,回合中插话应当“当前这步跑完就插”
|
||||
`disable` 连 `tools/list` 都不发。旧字段 `enable` 已废弃,`mode: silent` 已移除,
|
||||
出现即报配置错(不静默忽略)。
|
||||
- `executeTool(baseCtx, name, args)`:先查 `HANDLERS` 表,未命中再交给 MCP 注册表。
|
||||
`ctx = {sessionId, taskDir, run, cfg, db, vision}`;工具返回字符串,`read_file` 读图时返回
|
||||
`ctx = {sessionId, taskDir, workDir, run, cfg, db, vision}`;工具返回字符串,`read_file` 读图时返回
|
||||
`{text, image_rel}`(`text` 是结构化 JSON 回执,由 engine 转成 `image_ref` 块)。
|
||||
`workDir` = 会话手选的工作目录(本地端新建会话可选),空串时 `taskDir` 就是默认的
|
||||
`workspace_root/<会话id>`。
|
||||
- **路径沙箱**:所有路径经 `resolveInTask` 解析到 `taskDir` 内;`/tmp` 会被映射到
|
||||
`<taskDir>/.tmp`(与 executor 容器里 `/tmp` 的 bind 对齐)。符号链接越界一律拒绝。
|
||||
例外:`AGENT_FILE_SCOPE=workspace`(本地端 `local/start.sh` 注入)把业务工具的根放宽到
|
||||
`workspace_root`,且 `/tmp` 不重写、直接放行(本地 terminal 写的是真 `/tmp`);
|
||||
会话若手选了目录(`sessions.work_dir` 非空),业务工具与文件 API 的根都取那个真实目录
|
||||
(`fsRoot` 优先返回 `ctx.workDir`),且不再创建 `task-*` 子目录;
|
||||
路由层(文件 API / 公网短链 / data-page)与 `@会话` 仍按 `taskDir` 校验,不随之外扩。
|
||||
- **跨会话只读**:`@<session-id>/<rel>` 只允许 `list_directory`、`read_file`、`copy_path` 的
|
||||
`source_path`,且只限同一用户的会话。写侧显式拒绝——否则会造出字面 `@task-x` 目录。
|
||||
- `checkToolArgs` + `unwrapToolArgs`:前者做结构性预检并生成 `errAck`,后者按 schema 逐层剥掉
|
||||
@@ -238,8 +245,9 @@ IM 用户在实时对话,回合中插话应当“当前这步跑完就插”
|
||||
get/run 指认技能,`args` 仅 run 用;条件必填写不进 schema,由 `toolSkill` 校验并点名。
|
||||
`toolSkill` 在入口把旧字段名 `input_args` 归一化成 `args`,之后只走一条分派路径
|
||||
(曾有两条路径,其中一条只读 `input_args`,会静默丢参)。
|
||||
`input_schema.required` 在 `run` 前校验;相对路径参数按会话目录转绝对路径;入口一律用绝对路径
|
||||
(远端 cwd 是会话目录)。配了 executor 就走 `remote-exec`,否则本地 `spawn`。
|
||||
`input_schema.required` 在 `run` 前校验;相对路径参数按会话目录转绝对路径;入口一律用绝对路径,
|
||||
cwd 也一律是会话目录(本地 spawn 与远端一致,否则按 cwd 干活的技能会写到技能目录里)。
|
||||
配了 executor 就走 `remote-exec`,否则本地 `spawn`。
|
||||
模型可见的技能清单是 `listCallableSkills`(目录技能 + `mode=skill` 的 MCP 工具,同名时目录胜出);
|
||||
设置页的技能 API 仍只用 `listSkills`(按目录增删改),两者不要混用。
|
||||
mode=skill 的 MCP 技能在 `runSkill` 里位于 `absolutizeArgs` **之前**:直接 `mcp.callTool` 转发
|
||||
@@ -379,7 +387,10 @@ preview-proxy.mount(末尾兜底)
|
||||
|
||||
**改 prompt / profile**
|
||||
|
||||
- 默认 prompt:`templates/profile-default.txt`(`{APP_SKILLS_SECTION}` 占位技能清单)。
|
||||
- 默认 prompt:`templates/profile-default.txt`(`{APP_SKILLS_SECTION}` 占位技能清单,
|
||||
`{APP_ENV_SECTION}` 占位环境段)。
|
||||
- 环境段:`templates/env-server.txt`(executor 容器形态)/ `env-local.txt`(本机 spawn 形态),
|
||||
启动时按 `EXECUTOR_URL` 有无选定(`server.js` 的 `llm.setEnvMode`),改完重启。
|
||||
- 压缩/标题指令:`templates/prompt-compress.txt` / `prompt-title.txt`。
|
||||
- 自定义组合:`config.yml` 的 `model_profiles` + 模型的 `profile: <名>`;改完重启。
|
||||
|
||||
|
||||
@@ -2,6 +2,22 @@ FROM node:20-slim
|
||||
|
||||
ENV TZ=Asia/Shanghai
|
||||
|
||||
# git:Git 面板(提交历史 / 未提交改动)要读仓库,本机与容器共用同一条代码路径。
|
||||
# 国内构建慢:apt 默认源在国外,apt-get update 能卡十几分钟。默认换成腾讯云镜像(与 executor 同源)。
|
||||
# 境外构建或想换源:docker compose build --build-arg DEBIAN_MIRROR=deb.debian.org
|
||||
ARG DEBIAN_MIRROR=mirrors.cloud.tencent.com
|
||||
|
||||
# 换 apt 源:bookworm 可能是 /etc/apt/sources.list,也可能是 deb822 的 /etc/apt/sources.list.d/*.sources,
|
||||
# 直接 grep 扫一遍、只替换域名,两种格式都盖住(路径 /debian、/debian-security 保持不变)。
|
||||
RUN set -eux; \
|
||||
files="$(grep -rl 'deb.debian.org' /etc/apt/ 2>/dev/null || true)"; \
|
||||
if [ -n "$files" ]; then sed -i "s|deb.debian.org|${DEBIAN_MIRROR}|g" $files; fi
|
||||
|
||||
# 装完清 apt 列表,不给镜像多留几十 MB。
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends git \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# 国内构建慢:npm 默认源在国外。默认换成腾讯云 npm 镜像(与宿主机 ~/.npmrc 一致)。
|
||||
|
||||
@@ -46,7 +46,7 @@ agent:
|
||||
max_tool_iterations: 100 # 单轮最大迭代数(含工具调用)
|
||||
max_retries: 2 # 上游失败重试次数
|
||||
language: "Simplified Chinese" # 强制回复语言;留空不限
|
||||
auto_compress_tokens: 60000 # In token 超此值弹「自动压缩」提议;0=关
|
||||
auto_compress_tokens: 0 # In token 超此值弹「自动压缩」提议;0=关(默认关)
|
||||
# 历史重放占位裁剪(省 token):把「可再生的重负载」换成单行占位再发给上游
|
||||
#(DB/UI 不动,盘上可重读/重抓)。两个距离条件**同时满足**才裁:
|
||||
# rounds = 这一行之后又出现了几条 AI 回复 (「后面 AI 又说了几句话」)
|
||||
|
||||
Generated
+157
-157
File diff suppressed because it is too large
Load Diff
+9
-1
@@ -104,6 +104,12 @@ function createAuth(cfg) {
|
||||
let users = (cfg.auth && cfg.auth.users) || [];
|
||||
if (!users.length) {
|
||||
// 未启用认证 = 单用户自用:管理接口按「本机主人」放行,用户 CRUD 由 routes/users.js 自己拒绝。
|
||||
// /api/me 在关闭分支里也必须存在:前端靠它一次请求判定形态(auth:false = 未启用),
|
||||
// 若这里不注册,本地模式(无认证)下浏览器网络面板会永远挂着一条红色 404,
|
||||
// 也无法区分「路由不存在」和「cookie 失效」——后者才该跳登录页。
|
||||
router.get('/api/me', (req, res) => {
|
||||
res.json({ user: null, role: 'admin', model: '', auth: false });
|
||||
});
|
||||
return {
|
||||
enabled: false,
|
||||
middleware: (req, res, next) => next(),
|
||||
@@ -232,7 +238,9 @@ function createAuth(cfg) {
|
||||
// 与中间件同一解析顺序(cookie 优先),保证 /api/me 显示的用户与业务路由认定的用户一致
|
||||
const name = authUser(req);
|
||||
const row = name ? userRow(name) : null;
|
||||
res.json({ user: name, role: row ? row.role : '', model: row ? (row.model || '') : '' });
|
||||
// auth:true 让前端明确区分「启用了认证但当前无登录」(user:null → 跳登录)
|
||||
// 与「根本没启用认证」(auth:false → 单用户自用)这两种 user:null。
|
||||
res.json({ user: name, role: row ? row.role : '', model: row ? (row.model || '') : '', auth: true });
|
||||
});
|
||||
|
||||
// ----- 登录页 / 登出跳转 -----
|
||||
|
||||
@@ -83,7 +83,7 @@ const DEFAULTS = {
|
||||
// allow_private=false 开 SSRF 防护:目标主机名解析到回环/私有/链路本地地址即拒绝(重定向逐跳复查);
|
||||
// 确需抓内网服务再显式开 true(注意 DNS 重绑定属残余风险)。
|
||||
fetch: { timeout_ms: 30000, max_bytes: 1048576, max_chars: 12000, max_chars_hard: 64000, allow_private: false },
|
||||
// auto_compress_tokens:本轮 In token 峰值 ≥ 此值时推送「自动压缩」提议(0=关)。
|
||||
// auto_compress_tokens:本轮 In token 峰值 ≥ 此值时推送「自动压缩」提议(0=关,默认关)。
|
||||
// auto_complete_ms:held(保持中)超过此时长自动收口为 completed(0=关)。key 非独占后 held 不占任何资源,
|
||||
// 收口是纯视觉动作:历史/绑定不动,再发言照常由 completed 分支续跑(见 engine.sweepHeldTimeouts)。
|
||||
// 历史重放占位裁剪(llm.buildMessages):trim.rules 逐条声明「哪个工具、参数侧还是回执侧、
|
||||
@@ -93,7 +93,7 @@ const DEFAULTS = {
|
||||
// turns = 这一行之后又来了几条真人消息(role=user 且 type 为空,「后面又来了几条真人消息」)
|
||||
// 所以 turns:1 = 回合内绝不裁、跨过用户回合边界才裁(避免长回合里模型反复重读同一个文件)。
|
||||
// 这里是默认策略的唯一来源:config.yml 写了 trim.rules 就整体替换(写 [] = 全关)。
|
||||
agent: { temperature: 1.0, max_tool_iterations: 100, max_retries: 2, language: 'Simplified Chinese', auto_compress_tokens: 60000, auto_complete_ms: 1800000, trim: {
|
||||
agent: { temperature: 1.0, max_tool_iterations: 100, max_retries: 2, language: 'Simplified Chinese', auto_compress_tokens: 0, auto_complete_ms: 1800000, trim: {
|
||||
min_chars: 600,
|
||||
rules: [
|
||||
// 参数正文只是写盘时的快照:不带 turns,回合内也照裁(省的是每轮重发整个文件)
|
||||
@@ -236,6 +236,9 @@ function normalizePlatforms(rawPlatforms, profileNames) {
|
||||
// 非空时发请求前给历史 assistant 行挂该字段;空(缺省)= 不回传。纯发送侧旋钮,
|
||||
// 与接收解析无关(接收早已兼容 reasoning/reasoning_content 双名)。
|
||||
reasoning_ack_field: typeof m.reasoning_ack_field === 'string' ? m.reasoning_ack_field.trim() : '',
|
||||
// 选填:自动压缩阈值(用户自定义的「上下文用量线」,**不是**模型真实窗口)。
|
||||
// 回合内 In token 峰值达到它即自动压缩上下文(见 engine.runLoopInner 循环顶部);0/未配 = 不启用。
|
||||
max_context: Math.max(0, parseInt(m.max_context, 10) || 0),
|
||||
profile,
|
||||
});
|
||||
}
|
||||
@@ -359,6 +362,7 @@ function parseAndValidate(rawText, configPath) {
|
||||
display_name: m.display_name, vision: m.vision, enable: m.enable,
|
||||
extra_params: m.extra_params, thinking_params: m.thinking_params,
|
||||
reasoning_ack_field: m.reasoning_ack_field,
|
||||
max_context: m.max_context,
|
||||
profile: m.profile,
|
||||
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,
|
||||
|
||||
@@ -20,6 +20,7 @@ function initDb(dbPath) {
|
||||
assistant_type TEXT DEFAULT 'secretary',
|
||||
user TEXT DEFAULT '',
|
||||
profile TEXT DEFAULT '',
|
||||
deep_think INTEGER NOT NULL DEFAULT 0,
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL,
|
||||
completed_at INTEGER,
|
||||
@@ -231,6 +232,11 @@ function initDb(dbPath) {
|
||||
// 迁移:title_locked 用户手动重命名过标题(renameSession 置 1):显式留痕「名字是用户起的」,
|
||||
// 不得静默冲掉;清空会话时随标题一并复位(旧名字已文不对题)。
|
||||
if (!cols.some(c => c.name === 'title_locked')) db.exec("ALTER TABLE sessions ADD COLUMN title_locked INTEGER NOT NULL DEFAULT 0");
|
||||
// 迁移:会话级工作目录(本地桌面端新建会话时手选一个真实目录)。空串 = 沿用
|
||||
// workspace_root/<会话id>;服务器形态永远为空,行为与旧版完全一致(见 engine.taskDirOf)。
|
||||
if (!cols.some(c => c.name === 'work_dir')) db.exec("ALTER TABLE sessions ADD COLUMN work_dir TEXT NOT NULL DEFAULT ''");
|
||||
// 迁移:会话级深度思考开关(发消息时按请求体落库;重进会话回填按钮,压缩回合也以它为准)。
|
||||
if (!cols.some(c => c.name === 'deep_think')) db.exec('ALTER TABLE sessions ADD COLUMN deep_think INTEGER NOT NULL DEFAULT 0');
|
||||
// 迁移:wechat_bindings 补 deep_think 列——微信端全局深度思考开关(routes/channel.js /think 读写,
|
||||
// 投递时作为既有 deepThink 参数的取值来源);默认 0=关(与 H5 按钮初始态一致,/think on 手动开)。
|
||||
// 旧库若曾按 DEFAULT 1 补过列(当时默认开,存量行都是默认值回填而非用户显式选择),
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
'use strict';
|
||||
|
||||
const path = require('path');
|
||||
const log = require('./log');
|
||||
|
||||
// Content-Disposition 手工构造,绕开 content-disposition 包的 ASCII 兜底:
|
||||
// 该包会把中文名逐字替换成 ?(???.pdf),且 filename= 后紧跟 filename*= 会让
|
||||
@@ -53,10 +54,36 @@ function noStore(res) {
|
||||
res.setHeader('Expires', '0');
|
||||
}
|
||||
|
||||
// sendFile 失败的统一出口(所有调用方共用,不再各自 try/catch——sendFile 的失败是
|
||||
// **异步**回调,调用方外层的 try/catch 根本抓不到)。
|
||||
//
|
||||
// 为什么必须有人接:没人接就落进 Express 默认错误处理器,而它在 NODE_ENV != production 时
|
||||
// 会把 err.stack 拼成 HTML 页面吐给请求方——服务端绝对路径、源码文件名+行号、依赖版本全在
|
||||
// 里面。/p/<id> 是匿名可达端点(public-files.js 挂在 auth 之前),一次失败就等于把内部结构
|
||||
// 公开。所以正文只留一行固定文案,细节进日志。
|
||||
//
|
||||
// 4xx 一律折叠成 404:不向匿名取用方区分「不存在」与「无权限」(原来的 403/416 会变成
|
||||
// 探针,能区分路径是否存在)。
|
||||
function sendFileError(res, err, abs) {
|
||||
const code = Number(err && err.status);
|
||||
const notFound = !!err && (err.code === 'ENOENT' || (code >= 400 && code < 500));
|
||||
const status = notFound ? 404 : 500;
|
||||
log.warn('download', (notFound ? '取不到文件:' : '发送失败:') + abs +
|
||||
'(' + ((err && (err.code || err.message)) || err) + ')');
|
||||
if (res.headersSent) { if (res.destroy) res.destroy(); return; } // 已吐了半截,只能断开
|
||||
res.removeHeader('Content-Disposition'); // 进来前已按附件设过,错误响应不该带文件名
|
||||
res.status(status).type('text').send(notFound ? 'not found' : 'internal error');
|
||||
}
|
||||
|
||||
function sendDownload(res, abs) {
|
||||
noStore(res);
|
||||
res.setHeader('Content-Disposition', downloadDisposition(path.basename(abs)));
|
||||
res.sendFile(abs, { lastModified: false, etag: false, maxAge: 0 });
|
||||
// dotfiles:'allow' 与下面的图片分支对齐。send 默认 'ignore' 会把 .env / .gitignore 这类
|
||||
// 文件当成"不存在"抛 NotFoundError——文件明明在,取用方却拿到 404,且历史版本还会连带
|
||||
// 把堆栈页吐出去(见 sendFileError)。点文件本来就是我们自己签发的,没有理由拒绝。
|
||||
res.sendFile(abs, { dotfiles: 'allow', lastModified: false, etag: false, maxAge: 0 }, function (err) {
|
||||
if (err) sendFileError(res, err, abs);
|
||||
});
|
||||
}
|
||||
|
||||
// 内联图片响应(公网链 GET /p/<id> 的图片分支):点开链接直接显示,不再被当成附件下载。
|
||||
@@ -72,7 +99,10 @@ function sendInlineImage(res, abs, type) {
|
||||
// sandbox 不给 allow-scripts,退化成不可执行、无同源权限的文档;<img> 引用本就不执行脚本,不受影响。
|
||||
if (type === 'image/svg+xml') res.setHeader('Content-Security-Policy', 'sandbox');
|
||||
// dotfiles 显式放行:read_file 的压缩产物在 .imgcache/(点目录),默认策略对其他调用方不保证。
|
||||
res.sendFile(abs, { dotfiles: 'allow', lastModified: false, etag: false, maxAge: 0 });
|
||||
// 回调同 sendDownload:图片也可能在读盘中途失败(被删/EACCES),不能漏给默认错误处理器。
|
||||
res.sendFile(abs, { dotfiles: 'allow', lastModified: false, etag: false, maxAge: 0 }, function (err) {
|
||||
if (err) sendFileError(res, err, abs);
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { contentDisposition, downloadDisposition, sendDownload, sendInlineImage, inlineImageType };
|
||||
|
||||
+206
-20
@@ -53,8 +53,41 @@ function genTaskId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
// 会话级工作目录:本地桌面端新建会话时可手选一个真实目录(DB 列 work_dir,见 db.js 迁移)。
|
||||
// 空串 = 沿用 workspace_root/<会话id>,服务器形态永远走这条,行为与 v2.5.0 完全一致。
|
||||
// 用缓存的 prepared statement:taskDirOf 在文件 API / 工具链里被高频调用,每次现 prepare 没必要。
|
||||
let stmtWorkDir = null;
|
||||
function sessionWorkDir(sessionId) {
|
||||
try {
|
||||
if (!stmtWorkDir) stmtWorkDir = db.prepare('SELECT work_dir FROM sessions WHERE id = ?');
|
||||
const row = stmtWorkDir.get(sessionId);
|
||||
return String((row && row.work_dir) || '');
|
||||
} catch (_) { return ''; }
|
||||
}
|
||||
|
||||
function taskDirOf(sessionId) {
|
||||
return path.join(cfg.workspace_root, sessionId);
|
||||
return sessionWorkDir(sessionId) || path.join(cfg.workspace_root, sessionId);
|
||||
}
|
||||
|
||||
// 校验并归一化「手选工作目录」:必须已存在的真实目录(不替用户 mkdir),且不能是根目录 /
|
||||
// 或平台数据目录——后者存着 SQLite(.agent.db)和 prompt dump,让会话目录指过去等于让 AI
|
||||
// 直接动运行数据库。用户主目录/Linux 根下子目录不拦(本地模式本来就没沙箱,README 已提示
|
||||
// 选专用目录),但选到根目录本身无意义。
|
||||
function normalizeWorkDir(input) {
|
||||
const raw = String(input || '').trim();
|
||||
if (!raw) return '';
|
||||
if (!path.isAbsolute(raw)) throw Object.assign(new Error('工作目录必须是绝对路径:' + raw), { status_code: 400 });
|
||||
let real;
|
||||
try { real = fs.realpathSync(raw); } catch (_) { throw Object.assign(new Error('工作目录不存在:' + raw), { status_code: 400 }); }
|
||||
let st;
|
||||
try { st = fs.statSync(real); } catch (_) { throw Object.assign(new Error('工作目录不可访问:' + raw), { status_code: 400 }); }
|
||||
if (!st.isDirectory()) throw Object.assign(new Error('不是目录:' + raw), { status_code: 400 });
|
||||
if (real === path.parse(real).root) throw Object.assign(new Error('不能把根目录作为工作目录'), { status_code: 400 });
|
||||
const dataRoot = String(cfg.data_root || '');
|
||||
if (dataRoot && (real === dataRoot || real.startsWith(dataRoot + path.sep))) {
|
||||
throw Object.assign(new Error('不能选择平台数据目录作为工作目录'), { status_code: 400 });
|
||||
}
|
||||
return real;
|
||||
}
|
||||
|
||||
function getSession(sessionId) {
|
||||
@@ -172,9 +205,44 @@ function syncModelPool() {
|
||||
// 进程重启后:key 非独占,所有会话的绑定保持不动(顶部展示的模型持续可见,直到用户手动断开/换绑)。
|
||||
// active(重启后必无回合进程)与遗留 queued 会话统一归位 held;指向已被删除/禁用模型的绑定,
|
||||
// 下次发消息时由 ensureBinding 自动改选(优先留原平台),用户无感。
|
||||
// 归位前先把「回合没走完」的 active 挑出来:stop/重启打断时它们停在半路,最后一条非 tool 消息
|
||||
// 必是 user(模型还没答)或带 tool_calls 的 assistant(这批工具之后没了下文)。
|
||||
// 已答完、只是没来得及 finalize 的会话(最后是纯文本 assistant)不在此列,照常归位 held。
|
||||
const resumeIds = [];
|
||||
for (const r of db.prepare("SELECT id FROM sessions WHERE status='active'").all()) {
|
||||
const last = db.prepare(
|
||||
"SELECT role, tool_calls FROM messages WHERE session_id = ? AND role != 'tool' ORDER BY id DESC LIMIT 1"
|
||||
).get(r.id);
|
||||
if (last && (last.role === 'user'
|
||||
|| (last.role === 'assistant' && last.tool_calls && last.tool_calls !== '[]'))) resumeIds.push(r.id);
|
||||
}
|
||||
db.prepare('UPDATE model_pool SET is_busy = 0, current_session_id = NULL').run(); // 旧版独占列清残留(调度已不读)
|
||||
db.prepare("UPDATE sessions SET status='held', held_at=COALESCE(held_at, updated_at), updated_at=? WHERE status IN ('active','queued')").run(now());
|
||||
startHeldSweeper();
|
||||
// 续跑:不伪造工具执行结果,但给中断点那批调用补一条「服务重启、结果未知」的回执,
|
||||
// 否则 buildMessages 会把整行 tool_calls 丢掉,模型看不到自己发过什么命令,重启类任务就会无限重试。
|
||||
// 等 5s 是因为 init 早于 server.listen,executor 也可能还在起,太早开跑首轮工具只会拿到连接错误。
|
||||
const RESUME_DELAY_MS = 5000;
|
||||
for (const id of resumeIds) {
|
||||
setTimeout(() => {
|
||||
const s = getSession(id);
|
||||
// 5s 内用户可能已经自己发消息(已开跑)或点了停止:只接管仍停在 held/active 的会话
|
||||
if (!s || (s.status !== 'held' && s.status !== 'active')) return;
|
||||
try {
|
||||
ensureBinding(s);
|
||||
touch(id, { status: 'active', held_at: null, completed_at: null, cancelled_at: null });
|
||||
getRun(id, true).deepThink = !!s.deep_think; // 恢复中断前的深度思考开关(会话行里持久化的值)
|
||||
const n = markInterruptedBatch(id); // 先补中断点的回执,模型才能看到自己发过什么命令
|
||||
if (n) log.info('tool', id + ' 重启续跑前补齐 ' + n + ' 条中断回执');
|
||||
emitStatus(id);
|
||||
runLoop(id);
|
||||
log.info('engine', id + ' 重启后续跑未完成的回合');
|
||||
} catch (e) {
|
||||
log.warn('engine', id + ' 重启续跑失败:' + (e && e.message || e));
|
||||
}
|
||||
}, RESUME_DELAY_MS);
|
||||
}
|
||||
if (resumeIds.length) log.info('engine', '检测到 ' + resumeIds.length + ' 个被中断的回合,就绪后自动续跑');
|
||||
}
|
||||
|
||||
// ---------- 会话闲置处理(30min held 归档 + 4h 记忆收口) ----------
|
||||
@@ -319,6 +387,32 @@ function modelVision(session) {
|
||||
return !!(m && m.vision);
|
||||
}
|
||||
|
||||
// 会话绑定模型的自动压缩阈值(models[].max_context,0=未配→不自动压缩)。
|
||||
// 它不是模型真实上下文窗口,而是用户自己设的「用量线」——到线就压,与真实窗口多大无关。
|
||||
function modelMaxContext(session) {
|
||||
const m = session.model_id && (cfg.models || []).find(x => x.id === session.model_id);
|
||||
return (m && Number(m.max_context)) || 0;
|
||||
}
|
||||
|
||||
// 回合起点播种回合一开局的 In token:取「上一回合最后一次上游实报的 prompt_tokens」。
|
||||
// 不播种的话新回合第一个判据永远是 0(run.turnMaxPt 在 runLoop 里清零),
|
||||
// 历史早就超线也照样把整段再发一遍,只有等到本回合内出现工具迭代才补判——
|
||||
// 实测 123903 ≥ 120000 的那一发就是白打的(无 tool_calls 的回合到头来一发都不压)。
|
||||
// 摘要行的 usage 是「压缩请求自身」的用量(含被截断的旧转写),不代表压缩后的上下文,
|
||||
// 拿它播种会让刚压完立刻再压,故只认最新摘要之后的行。
|
||||
function seedTurnMaxPt(sessionId) {
|
||||
const last = db.prepare("SELECT MAX(id) AS id FROM messages WHERE session_id = ? AND type = 'summary'").get(sessionId);
|
||||
const row = db.prepare(
|
||||
"SELECT usage FROM messages WHERE session_id = ? AND role = 'assistant' AND usage IS NOT NULL" +
|
||||
" AND id > ? ORDER BY id DESC LIMIT 1"
|
||||
).get(sessionId, (last && last.id) || 0);
|
||||
if (!row || !row.usage) return 0;
|
||||
try {
|
||||
const u = JSON.parse(row.usage);
|
||||
return Math.max(0, Number(u && u.pt) || 0);
|
||||
} catch (_) { return 0; }
|
||||
}
|
||||
|
||||
// ---------- 模型 profile(prompt+tools 组合) ----------
|
||||
// 把 cfg 里预加载的自定义 prompt 文本注册给 llm(配置加载时已读入,见 config.js);
|
||||
// engine.init 调一次,运行期只按名选取,零 IO。
|
||||
@@ -513,7 +607,7 @@ async function runLoop(sessionId) {
|
||||
if (run.looping) return; // 已有循环在跑(下一轮迭代会自动带上最新消息)
|
||||
run.looping = true;
|
||||
// 回合级 In token 峰值(整轮结束后供自动压缩检查);记录本回合是否为压缩回合,压缩回合不再自启压缩防递归
|
||||
run.turnMaxPt = 0;
|
||||
run.turnMaxPt = seedTurnMaxPt(sessionId);
|
||||
const wasCompressTurn = !!run.summarizing;
|
||||
try {
|
||||
await runLoopInner(sessionId, run);
|
||||
@@ -528,6 +622,34 @@ async function runLoop(sessionId) {
|
||||
}
|
||||
}
|
||||
|
||||
// 重启续跑前给中断点那批调用补回执:不伪造执行结果,只告知「服务重启、结果未知」。
|
||||
// 有了配对回执,buildMessages 才会保留整行 tool_calls——否则它会把无回执的调用剔掉,
|
||||
// 模型看不到自己发过什么命令,「重启」类任务就靠猜,猜错就无限重试。
|
||||
function markInterruptedBatch(sessionId) {
|
||||
const last = db.prepare(
|
||||
"SELECT id, role, tool_calls FROM messages WHERE session_id = ? AND role != 'tool' ORDER BY id DESC LIMIT 1"
|
||||
).get(sessionId);
|
||||
if (!last || last.role !== 'assistant' || !last.tool_calls) return 0; // 收尾回复或用户才发完话
|
||||
let calls = [];
|
||||
try { calls = JSON.parse(last.tool_calls) || []; } catch (_) { return 0; }
|
||||
const got = new Set(
|
||||
db.prepare(
|
||||
"SELECT tool_call_id FROM messages WHERE session_id = ? AND role = 'tool' AND id > ? AND tool_call_id IS NOT NULL AND tool_call_id != ''"
|
||||
).all(sessionId, last.id).map(r => r.tool_call_id)
|
||||
);
|
||||
let n = 0;
|
||||
for (const c of calls) {
|
||||
if (!c || !c.id || got.has(c.id)) continue;
|
||||
const name = (c.function && c.function.name) || '未知工具';
|
||||
saveMessage(sessionId, {
|
||||
role: 'tool', tool_call_id: c.id, name,
|
||||
content: '[系统] 服务重启,本次调用被中断,执行结果未知:先核实实际状态再决定,不要直接重试。',
|
||||
});
|
||||
n++;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
function finalize(sessionId, run) {
|
||||
const s = getSession(sessionId);
|
||||
if (!s || s.status !== 'active') { runs.delete(sessionId); return; }
|
||||
@@ -631,6 +753,29 @@ function cleanTitle(raw) {
|
||||
return t.slice(0, 60);
|
||||
}
|
||||
|
||||
// 读图回传上游有两条取图路,取决于「谁能访问这个 URL」:
|
||||
// - 服务器形态:签一条公网短链(/p/<id>),模型厂商的服务器来拉;
|
||||
// - 本地形态:core 监听在回环地址,厂商拉不到 127.0.0.1,改为把压缩后的图内联成 data URL
|
||||
// (llm.js 侧本来就接受这个形态——用户粘贴附件的 image_url 走的就是它)。
|
||||
// 只认 AGENT_IMAGE_INLINE=1(local/start.sh 注入):服务器不设 → 完全走原路径。
|
||||
const INLINE_IMAGE_MAX_BYTES = 1.5 * 1024 * 1024;
|
||||
const INLINE_IMAGE_MIME = {
|
||||
'.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png',
|
||||
'.webp': 'image/webp', '.gif': 'image/gif',
|
||||
};
|
||||
|
||||
function inlineImageDataUrl(abs) {
|
||||
if (String(process.env.AGENT_IMAGE_INLINE || '') !== '1') return null;
|
||||
const mime = INLINE_IMAGE_MIME[path.extname(abs).toLowerCase()];
|
||||
if (!mime) return null;
|
||||
try {
|
||||
// 上限按原文件字节算(base64 约 1.34 倍):超限宁可不发——llm 侧会照旧降级成
|
||||
// 「像素未送达」——也不把请求体顶爆(.imgcache 产物已压到长边 2000px,正常远低于上限)。
|
||||
if (fs.statSync(abs).size > INLINE_IMAGE_MAX_BYTES) return null;
|
||||
return 'data:' + mime + ';base64,' + fs.readFileSync(abs).toString('base64');
|
||||
} catch (_) { return null; }
|
||||
}
|
||||
|
||||
async function runLoopInner(sessionId, run) {
|
||||
let iter = 0;
|
||||
// 已纳入模型请求的最大消息 id;用于判断是否有尚未被回应的新 user 消息
|
||||
@@ -642,21 +787,39 @@ async function runLoopInner(sessionId, run) {
|
||||
if (!session || session.status !== 'active' || !session.model_id) break;
|
||||
session.history = loadHistory(sessionId);
|
||||
for (const m of session.history) if (m.id > lastIncludedId) lastIncludedId = m.id;
|
||||
// 自动压缩:本回合已用到的 In token 峰值(上一轮上游实报值)达到模型配的 max_context,
|
||||
// 就地把握回合切成压缩回合——不新开 run、不发 auto_compress 提议,前端无感(产物就是摘要卡片,
|
||||
// 与手点「压缩」完全同一条路径:下一圈的 compressing 分支换 prompt、摘要落库归档)。
|
||||
// 检查点必须在请求发出之前:这个数字是上一轮的真实值,下一轮只会更大。
|
||||
// 压缩回合自身不再判(run.summarizing 已真),否则会把自己再压一遍。
|
||||
const maxCtx = modelMaxContext(session);
|
||||
if (maxCtx > 0 && !run.summarizing && (run.turnMaxPt || 0) >= maxCtx) {
|
||||
log.info('msg', sessionId + ' 自动压缩:回合 In ' + run.turnMaxPt + ' ≥ max_context ' + maxCtx);
|
||||
run.summarizing = true;
|
||||
// 标记「这是回合内自动压缩」:摘要落地后要接着跑完原任务(见 isSummary 分支),
|
||||
// 与用户手点「压缩」发起的独立压缩回合区分开(那种压完就该停)。
|
||||
run.compactAuto = true;
|
||||
}
|
||||
// 压缩回合(run.summarizing = 由「压缩」按钮发起、尚未产出摘要):
|
||||
// 沿用默认 system prompt + 正常历史,末尾追加一条压缩指令 user(见 llm.compressMessages);
|
||||
// 且不传 tools,模型只能输出摘要文本。
|
||||
// 沿用默认 system prompt + 正常历史 + 同一套 tools,末尾追加一条压缩指令 user(见 llm.compressMessages),
|
||||
// 请求与上一发常规请求只差尾部这一段,前缀缓存整段命中。
|
||||
// 发送前为历史里的 image_ref 块现签公网外链(GET /p/<id>,同 mint_public_link):
|
||||
// 每次请求重签,回合内多轮迭代/重试永不过期;DB 只存几十字符的 rel,base64 不进库不进请求体。
|
||||
// base_url 未配/校验不过/mint 异常时返回 null,buildMessages 降级为文字占位。
|
||||
// base_url 未配/校验不过/mint 异常时返回 null,buildMessages 降级为文字占位;本地形态
|
||||
// 没有公网前缀时改走内联 data URL(同见 inlineImageDataUrl),厂商拉不到回环地址。
|
||||
// image_rel 可能是压缩无收益时直指的原文件:与 mint_public_link 同款 realpath 复核,
|
||||
// 防任务目录里指向外部的符号链接图片被签上公网。
|
||||
const mintImageUrl = (rel) => {
|
||||
const pl = cfg.public_link || {};
|
||||
if (!pl.base_url) return null;
|
||||
let dir, real;
|
||||
try {
|
||||
const dir = taskDirOf(sessionId);
|
||||
const real = fs.realpathSync(resolveInTask(dir, rel));
|
||||
dir = taskDirOf(sessionId);
|
||||
real = fs.realpathSync(resolveInTask(dir, rel));
|
||||
if (real !== dir && !real.startsWith(dir + path.sep)) return null;
|
||||
} catch (_) { return null; }
|
||||
// 符号链接复核先做完再分叉:内联形态同样不能让任务目录外的图出去(见 inlineImageDataUrl)。
|
||||
if (!pl.base_url) return inlineImageDataUrl(real);
|
||||
try {
|
||||
return pl.base_url + '/p/' + publicFiles.mint({ sessionId: sessionId, rel, ttlMs: pl.ttl_ms });
|
||||
} catch (_) { return null; }
|
||||
};
|
||||
@@ -682,8 +845,9 @@ async function runLoopInner(sessionId, run) {
|
||||
+ (txt.includes('"already_delivered"') ? '[图重复读挡回]' : '');
|
||||
}).join(' '));
|
||||
}
|
||||
// 内置工具 + 启动时发现的 MCP 工具(按 profile 白名单过滤),一起随 system prompt 发给模型(压缩回合不发)
|
||||
const tools = compressing ? [] : effectiveTools(profileName);
|
||||
// 内置工具 + 启动时发现的 MCP 工具(按 profile 白名单过滤),一起随 system prompt 发给模型。
|
||||
// 压缩回合也照发:tools 段在最前,删掉等于断整段前缀缓存(尾部指令已写明不要调用工具)。
|
||||
const tools = effectiveTools(profileName);
|
||||
|
||||
let result = null;
|
||||
let lastErr = null;
|
||||
@@ -788,6 +952,9 @@ async function runLoopInner(sessionId, run) {
|
||||
// 后续对话从这条摘要开始,旧历史不再烧 token。
|
||||
// 旧摘要行(多轮压缩)一并存档:被新摘要覆盖替代,不再进上下文。
|
||||
run.summarizing = null;
|
||||
// 摘要已落地:清掉本回合的 In 峰值,后续轮次按压缩后的新上下文重新计量。
|
||||
// 不清就会拿旧值立刻再触发一次(死循环);清了则压完仍超还能再压(支持连续压缩)。
|
||||
run.turnMaxPt = 0;
|
||||
if ((msgRow.content || '').trim()) {
|
||||
db.prepare("UPDATE messages SET type = 'summary' WHERE id = ?").run(assistantId);
|
||||
const n = db.prepare(
|
||||
@@ -796,6 +963,16 @@ async function runLoopInner(sessionId, run) {
|
||||
).run(sessionId, assistantId).changes;
|
||||
log.info('msg', sessionId + ' 压缩摘要 ' + assistantId + ' 落库,存档之前 ' + n + ' 条消息(不再发给模型)');
|
||||
}
|
||||
// 回合内自动压缩把正在跑的任务切成了摘要,摘要一落地就地续跑:
|
||||
// 补一条 user 指令接回原任务,否则会直接走到下面的 !hasTools 收尾,
|
||||
// 任务停在半路,要用户再喊一声才动。
|
||||
if (run.compactAuto) {
|
||||
run.compactAuto = false;
|
||||
const resumeText = '上下文已压缩,请继续完成原任务。';
|
||||
const resumeId = saveMessage(sessionId, { role: 'user', content: resumeText });
|
||||
bus.emit(sessionId, 'user_message', { id: resumeId, content: resumeText, created_at: now() });
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasTools) {
|
||||
@@ -842,7 +1019,7 @@ async function runLoopInner(sessionId, run) {
|
||||
isError = true;
|
||||
} else {
|
||||
try {
|
||||
output = await executeTool({ sessionId, taskDir: taskDirOf(sessionId), run, cfg, db, vision,
|
||||
output = await executeTool({ sessionId, taskDir: taskDirOf(sessionId), workDir: sessionWorkDir(sessionId), run, cfg, db, vision,
|
||||
onTaskCreated: () => { run.taskWrap = true; }, onCard: (card) => bus.emit(sessionId, 'ui_card', card),
|
||||
onDeepThink: (info) => {
|
||||
const m = (cfg.models || []).find(x => x.id === session.model_id);
|
||||
@@ -1116,7 +1293,7 @@ function sleep(ms) { return new Promise(r => setTimeout(r, ms)); }
|
||||
// ---------- 对外 API ----------
|
||||
// 新建即绑模(无排队):指定了优先模型(welcome 预选)就取其平台「最不 active」的 key;
|
||||
// 模型无效或平台无槽位退回全局优先级选。池完全为空直接报错(配置问题),不建吊儿郎当的会话。
|
||||
function createSession(title, preferModelId, assistantType, user) {
|
||||
function createSession(title, preferModelId, assistantType, user, workDir) {
|
||||
// 用户锁定模型(auth.users[].model)优先于前端预选;锁定值无效/被禁用时退回原逻辑(用前端预选或全局自动选择)。
|
||||
const lock = lockedModelOf(user);
|
||||
const lockValid = !!lock && platformModels(platformOf(lock)).includes(lock);
|
||||
@@ -1137,11 +1314,13 @@ function createSession(title, preferModelId, assistantType, user) {
|
||||
if (!modelId) throw Object.assign(new Error('无可用模型:请检查配置并重启服务'), { status_code: 503 });
|
||||
}
|
||||
const id = genTaskId();
|
||||
const dir = taskDirOf(id);
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
// 手选目录:直接当作会话工作目录(不建 task-* 子目录);未选 = 沿用 workspace_root/<会话id>。
|
||||
// 选中的目录必须已存在(normalizeWorkDir 已校验),绝不在用户目录里替它 mkdir。
|
||||
// 两种情况下目录都由工具执行时懒建(见 tools/executor.js 的 executeTool),纯文本对话不留空目录。
|
||||
const wd = normalizeWorkDir(workDir);
|
||||
db.prepare(
|
||||
"INSERT INTO sessions (id, title, status, model_id, model_slot, last_model_id, held_at, assistant_type, user, created_at, updated_at) VALUES (?,?,'held',?,?,?,?,?,?,?,?)"
|
||||
).run(id, title || '', modelId, key.id, modelId, now(), assistantType || 'secretary', user || '', now(), now());
|
||||
"INSERT INTO sessions (id, title, status, model_id, model_slot, last_model_id, held_at, assistant_type, user, work_dir, created_at, updated_at) VALUES (?,?,'held',?,?,?,?,?,?,?,?,?)"
|
||||
).run(id, title || '', modelId, key.id, modelId, now(), assistantType || 'secretary', user || '', wd, now(), now());
|
||||
db.prepare('UPDATE model_pool SET last_used_at = ? WHERE id = ?').run(now(), key.id);
|
||||
profile.freezeSnapshot(db, id); // 冻结画像快照:仅创建/清空时点注入,会话内恒定(见 user-profile.js)
|
||||
// 新建会话默认走模型配置的 profile(未配 = 全量默认组合 + profile-default.txt),不再有顾问阶段
|
||||
@@ -1298,6 +1477,8 @@ function postUserMessage(sessionId, content, opts) {
|
||||
// 预建/更新 run 记录,记下本轮的 deepThink(被 runLoop / callModel 读取)
|
||||
const run = getRun(sessionId, true);
|
||||
run.deepThink = !!(opts && opts.deepThink);
|
||||
// 随消息落库:重进会话按它回填按钮,压缩回合也读它
|
||||
db.prepare('UPDATE sessions SET deep_think = ? WHERE id = ?').run(run.deepThink ? 1 : 0, sessionId);
|
||||
// 真实用户消息到达:若还有个「尚未开跑」的压缩回合(见 summarizeContext),
|
||||
// 让它作废,避免新消息被误当成压缩回合处理;已在跑(looping)的不动,
|
||||
// 由其收尾时自行清空 summarizing。
|
||||
@@ -1358,6 +1539,9 @@ function renameSession(sessionId, title) {
|
||||
function deleteSession(sessionId, deleteDir) {
|
||||
const session = getSession(sessionId);
|
||||
if (!session) throw Object.assign(new Error('会话不存在'), { status_code: 404 });
|
||||
// 删行前先取目录:行没了 taskDirOf 会退回默认路径,且手选目录根本不归平台管。
|
||||
const sessionDir = taskDirOf(sessionId);
|
||||
const ownWorkDir = String(session.work_dir || '');
|
||||
stop(sessionId);
|
||||
// 尽力清理该会话在 executor 侧的预览槽(officecli 预览已迁 executor/preview.js;未配 executor 静默,失败只记日志不阻断删除)
|
||||
try { rexec.killPreviewSession(cfg, sessionId); } catch (_) {}
|
||||
@@ -1367,8 +1551,10 @@ function deleteSession(sessionId, deleteDir) {
|
||||
const frags = memory.dropFragment(db, sessionId); // 日记随会话一并销毁:删掉的会话不该还活在长期记忆里
|
||||
if (frags) log.info('task', sessionId + ' 连带删除日记碎片 ' + frags + ' 条');
|
||||
autoCompressProposed.delete(sessionId); // 提议闸门随会话销毁
|
||||
if (deleteDir) {
|
||||
try { fs.rmSync(taskDirOf(sessionId), { recursive: true, force: true }); } catch (_) {}
|
||||
if (deleteDir && !ownWorkDir) {
|
||||
// 只删平台自己建的会话目录(workspace_root/<会话id>)。手选工作目录是用户的资产,
|
||||
// 多个会话可以共用同一个目录,删会话绝不能连带删用户的项目。
|
||||
try { fs.rmSync(sessionDir, { recursive: true, force: true }); } catch (_) {}
|
||||
}
|
||||
bus.closeAll(sessionId);
|
||||
return { ok: true };
|
||||
@@ -1396,10 +1582,10 @@ function summarizeContext(sessionId) {
|
||||
}
|
||||
const prompt = '正在压缩上下文:AI 将基于完整对话记录生成摘要…';
|
||||
// 与 postUserMessage 同样的唤醒语义(不再排队、不落消息行);run.summarizing 标记本回合为压缩回合,摘要产出后由 runLoopInner 清空。
|
||||
// 状态流转时顺带重置 deepThink:压缩回合不需要思考参数,避免沿用上一轮的残留值。
|
||||
// 思考参数跟会话当前状态(由发消息时落库),换开关就换请求体,历史字节不受影响。
|
||||
const r = getRun(sessionId, true);
|
||||
r.summarizing = true;
|
||||
r.deepThink = false;
|
||||
r.deepThink = !!session.deep_think;
|
||||
ensureBinding(session);
|
||||
touch(sessionId, { status: 'active', held_at: null, completed_at: null, cancelled_at: null });
|
||||
emitStatus(sessionId);
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
// 统一 HTTP 错误出口(Express 的四参数错误中间件,必须在所有路由之后注册)。
|
||||
//
|
||||
// 存在理由:Express 默认错误处理器只有 NODE_ENV=production 时才回一句干净的 500,
|
||||
// 其余环境把 err.stack 拼成 HTML 吐给请求方——里面是服务端绝对路径、源码文件名+行号、
|
||||
// 依赖版本。本地形态 NODE_ENV 通常未设置,等于默认开启。而 /p/<id> 这类端点匿名可达
|
||||
// (见 routes/public-files.js),一次 sendFile 失败就能把整份栈打到公网。
|
||||
//
|
||||
// 策略:状态码照旧透出(body-parser 的 400/413、send 的 404 都靠它,客户端要能区分),
|
||||
// 正文永远固定一句,栈只进日志。
|
||||
'use strict';
|
||||
|
||||
const log = require('./log');
|
||||
|
||||
// 只认 err.status / err.statusCode 里的合法 4xx-5xx;其余(含没状态码的普通 Error)一律 500。
|
||||
function statusOf(err) {
|
||||
const s = Number(err && (err.status || err.statusCode));
|
||||
return s >= 400 && s <= 599 ? s : 500;
|
||||
}
|
||||
|
||||
function errorHandler(err, req, res, next) { // eslint-disable-line no-unused-vars
|
||||
const status = statusOf(err);
|
||||
const where = (req && req.method ? req.method + ' ' + (req.originalUrl || req.url || '') : '(unknown)');
|
||||
// 5xx = 未预期异常,栈进日志;4xx 是调用方问题,一行 message 足够。
|
||||
if (status >= 500) log.error('http', where + ' → ' + status + ':' + ((err && err.stack) || err));
|
||||
else log.warn('http', where + ' → ' + status + ':' + ((err && err.message) || err));
|
||||
|
||||
if (res.headersSent) { if (res.destroy) res.destroy(); return; } // 响应已开始,只能断开
|
||||
res.removeHeader('Content-Disposition'); // 可能已被 download-send 设过,错误体不该带文件名
|
||||
res.status(status).type('text').send(status >= 500 ? 'internal error' : 'request failed');
|
||||
}
|
||||
|
||||
module.exports = { errorHandler, statusOf };
|
||||
@@ -0,0 +1,280 @@
|
||||
// 只读 git 数据层:仓库探测 / 提交列表 / 提交详情 / 未提交改动详情。
|
||||
// 一律 execFile + 参数数组(不经 shell),只跑 rev-parse / status / log / show / diff,不碰任何写操作。
|
||||
// -c core.quotepath=false:中文路径原样返回,不转义成 \346\226\207 那种八进制。
|
||||
const { execFile } = require('child_process');
|
||||
const fs = require('fs');
|
||||
|
||||
const TIMEOUT = 8000;
|
||||
const MAX_BUFFER = 8 * 1024 * 1024;
|
||||
const PATCH_FILE_MAX = 120 * 1024; // 单文件 diff 字符上限
|
||||
const PATCH_TOTAL_MAX = 400 * 1024; // 整页 diff 字符上限
|
||||
const UNTRACKED_MAX_BYTES = 512 * 1024; // 未跟踪文件超过此大小不生成 diff
|
||||
const MAX_FILES = 300; // 一次最多返回的文件数
|
||||
|
||||
const BASE = ['-c', 'core.quotepath=false'];
|
||||
|
||||
function run(dir, args) {
|
||||
return new Promise((resolve, reject) => {
|
||||
// cwd 不存在时 execFile 也报 ENOENT,会和「没装 git」混为一谈,先自己挡掉
|
||||
let isDir = false;
|
||||
try { isDir = fs.statSync(dir).isDirectory(); } catch (_) { isDir = false; }
|
||||
if (!isDir) return reject(Object.assign(new Error('会话目录不存在'), { reason: 'not_repo' }));
|
||||
execFile('git', BASE.concat(args), { cwd: dir, timeout: TIMEOUT, maxBuffer: MAX_BUFFER }, (err, stdout, stderr) => {
|
||||
if (!err) return resolve(stdout);
|
||||
err.stdout = String(stdout || '');
|
||||
err.stderr = String(stderr || '').trim();
|
||||
reject(err);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function reasonOf(err) {
|
||||
if (err && err.code === 'ENOENT') return 'no_git';
|
||||
if (err && err.code === 'ETIMEDOUT') return 'timeout';
|
||||
return 'not_repo';
|
||||
}
|
||||
|
||||
// 仓库信息:root 用 --show-toplevel(会话目录可能是仓库子目录);空仓库没有 HEAD,不算错。
|
||||
async function ensureRepo(dir) {
|
||||
let root;
|
||||
try {
|
||||
root = (await run(dir, ['rev-parse', '--show-toplevel'])).trim();
|
||||
} catch (err) {
|
||||
throw Object.assign(new Error(err.code === 'ENOENT' ? '未安装 git' : '当前目录不是 git 仓库'), { reason: reasonOf(err) });
|
||||
}
|
||||
if (!root) throw Object.assign(new Error('当前目录不是 git 仓库'), { reason: 'not_repo' });
|
||||
let branch = '';
|
||||
let head = '';
|
||||
try { branch = (await run(root, ['symbolic-ref', '--short', '-q', 'HEAD'])).trim(); } catch (_) { /* detached */ }
|
||||
try { head = (await run(root, ['rev-parse', '--short', 'HEAD'])).trim(); } catch (_) { /* 空仓库 */ }
|
||||
// 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` 切开,键是文件路径。
|
||||
// 路径优先取 `+++ b/...`(改后),删除文件取 `--- a/...`;都没有就等于没有内容变化(仅 mode 变更)。
|
||||
function patchPath(body) {
|
||||
const plus = body.match(/^\+\+\+ b\/(.+)$/m);
|
||||
if (plus) return plus[1].replace(/\t$/, '');
|
||||
const minus = body.match(/^--- a\/(.+)$/m);
|
||||
if (minus) return minus[1].replace(/\t$/, '');
|
||||
const head = body.match(/^diff --git a\/(.+) b\/(.+)$/m);
|
||||
return head ? head[2] : null;
|
||||
}
|
||||
|
||||
function splitPatch(text) {
|
||||
const out = new Map();
|
||||
if (!text) return out;
|
||||
const parts = String(text).split(/^diff --git /m);
|
||||
for (let i = 1; i < parts.length; i++) {
|
||||
const body = 'diff --git ' + parts[i];
|
||||
const p = patchPath(body);
|
||||
if (p) out.set(p, body);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function countLines(patch) {
|
||||
let adds = 0;
|
||||
let dels = 0;
|
||||
for (const line of String(patch).split('\n')) {
|
||||
if (line.charAt(0) === '+' && line.charAt(1) !== '+') adds++;
|
||||
else if (line.charAt(0) === '-' && line.charAt(1) !== '-') dels++;
|
||||
}
|
||||
return { adds, dels };
|
||||
}
|
||||
|
||||
function statusOf(patch, fallback) {
|
||||
if (/^new file mode /m.test(patch)) return 'A';
|
||||
if (/^deleted file mode /m.test(patch)) return 'D';
|
||||
if (/^rename from /m.test(patch) || /^copy from /m.test(patch)) return 'R';
|
||||
if (/^Binary files .* differ$/m.test(patch) || /^GIT binary patch$/m.test(patch)) return fallback || 'M';
|
||||
return fallback || 'M';
|
||||
}
|
||||
|
||||
function isBinary(patch) {
|
||||
return /^Binary files .* differ$/m.test(patch) || /^GIT binary patch$/m.test(patch);
|
||||
}
|
||||
|
||||
// 裁剪 + 汇总。逐文件先裁,再按总量裁(超出的文件保留路径与统计,patch 置空并标 truncated)。
|
||||
function buildFiles(map, order, extra) {
|
||||
const files = [];
|
||||
const byPath = new Map();
|
||||
let budget = PATCH_TOTAL_MAX;
|
||||
for (const p of order) {
|
||||
if (files.length >= MAX_FILES) break;
|
||||
const raw = map.get(p) || '';
|
||||
const binary = isBinary(raw);
|
||||
let patch = raw;
|
||||
let truncated = false;
|
||||
if (patch.length > PATCH_FILE_MAX) { patch = patch.slice(0, PATCH_FILE_MAX); truncated = true; }
|
||||
if (patch.length > budget) { patch = ''; truncated = true; }
|
||||
budget -= patch.length;
|
||||
const counts = binary ? { adds: 0, dels: 0 } : countLines(patch);
|
||||
const item = {
|
||||
path: p,
|
||||
status: extra && extra[p] ? extra[p].status : statusOf(raw, extra && extra[p] && extra[p].status),
|
||||
adds: counts.adds,
|
||||
dels: counts.dels,
|
||||
binary: binary,
|
||||
truncated: truncated,
|
||||
patch: binary ? '' : patch,
|
||||
};
|
||||
if (extra && extra[p] && extra[p].old_path) item.old_path = extra[p].old_path;
|
||||
files.push(item);
|
||||
byPath.set(p, item);
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
function summarize(files) {
|
||||
let adds = 0;
|
||||
let dels = 0;
|
||||
for (const f of files) { adds += f.adds; dels += f.dels; }
|
||||
return { stats: { files: files.length, adds, dels } };
|
||||
}
|
||||
|
||||
// git status --porcelain -z:拿未跟踪文件和状态字母(已跟踪文件的 patch 统一从 `diff HEAD` 拆)
|
||||
// -z 必须加:不加引号规则下含空格的路径会被写成 "a b.txt",和 diff 里的裸路径对不上,会多出幽灵条目。
|
||||
// -z 里改名的旧路径是紧随其后的一条 NUL 分隔记录。
|
||||
function worktreeEntries(out) {
|
||||
const entries = [];
|
||||
const parts = String(out || '').split('\0');
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
const line = parts[i];
|
||||
if (!line || line.length < 4) continue;
|
||||
const xy = line.slice(0, 2);
|
||||
const p = line.slice(3);
|
||||
let oldPath = '';
|
||||
if (/[RC]/.test(xy)) {
|
||||
oldPath = parts[i + 1] || '';
|
||||
i++;
|
||||
}
|
||||
let status = 'M';
|
||||
if (xy === '??') status = 'U';
|
||||
else if (xy.indexOf('A') >= 0) status = 'A';
|
||||
else if (xy.indexOf('D') >= 0) status = 'D';
|
||||
else if (xy.indexOf('R') >= 0) status = 'R';
|
||||
entries.push({ path: p, old_path: oldPath || undefined, status });
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
// 未跟踪文件没有 diff:用 --no-index 对 /dev/null 造一个(退出码 1 = 有差异,属正常)
|
||||
async function untrackedPatch(root, rel) {
|
||||
const abs = root + '/' + rel;
|
||||
try {
|
||||
const st = fs.statSync(abs);
|
||||
if (!st.isFile() || st.size > UNTRACKED_MAX_BYTES) return { patch: '', binary: st.size > UNTRACKED_MAX_BYTES };
|
||||
} catch (_) { return { patch: '', binary: false }; }
|
||||
try {
|
||||
return { patch: await run(root, ['diff', '--no-index', '--', '/dev/null', rel]), binary: false };
|
||||
} catch (err) {
|
||||
if (err.code === 1) return { patch: err.stdout, binary: false };
|
||||
return { patch: '', binary: false };
|
||||
}
|
||||
}
|
||||
|
||||
async function worktreeDetail(root) {
|
||||
let entries = [];
|
||||
try { entries = worktreeEntries(await run(root, ['status', '--porcelain', '-z'])); }
|
||||
catch (_) { entries = []; }
|
||||
let all = '';
|
||||
try { all = await run(root, ['diff', 'HEAD']); } catch (_) { all = ''; } // 空仓库没有 HEAD
|
||||
const map = splitPatch(all);
|
||||
const extra = {};
|
||||
for (const e of entries) extra[e.path] = e;
|
||||
const order = [];
|
||||
for (const e of entries) order.push(e.path);
|
||||
for (const p of map.keys()) if (!extra[p]) { extra[p] = { status: 'M' }; order.push(p); }
|
||||
for (const e of entries) {
|
||||
if (e.status !== 'U' || map.has(e.path)) continue;
|
||||
const r = await untrackedPatch(root, e.path);
|
||||
if (r.patch) map.set(e.path, r.patch);
|
||||
else if (r.binary) extra[e.path].binary = true;
|
||||
}
|
||||
const files = buildFiles(map, order, extra);
|
||||
return { kind: 'worktree', commit: null, files: files, ...summarize(files) };
|
||||
}
|
||||
|
||||
// git log:before 是上一页最后一条的 commit id,用 `<id>^` 翻页(git 天然不含自身)。
|
||||
async function listCommits(dir, before, limit) {
|
||||
const repo = await ensureRepo(dir);
|
||||
const n = Math.max(1, Math.min(100, limit || 30));
|
||||
const args = ['log', '--max-count=' + (n + 1), '--pretty=format:%H%x1f%h%x1f%an%x1f%aI%x1f%s'];
|
||||
if (before) args.push(before + '^', '--');
|
||||
let out = '';
|
||||
try { out = await run(repo.root, args); } catch (err) {
|
||||
if (before) return { ok: true, repo, worktree: null, commits: [], next: null }; // 已经翻到底
|
||||
if (reasonOf(err) === 'no_git') throw err;
|
||||
return { ok: true, repo, worktree: null, commits: [], next: null }; // 空仓库
|
||||
}
|
||||
const rows = out.split('\n').filter(Boolean).map((line) => {
|
||||
const f = line.split('\x1f');
|
||||
return { id: f[0], short: f[1], author: f[2], time: f[3], subject: f[4] || '' };
|
||||
});
|
||||
const hasMore = rows.length > n;
|
||||
const commits = hasMore ? rows.slice(0, n) : rows;
|
||||
const next = hasMore && commits.length ? commits[commits.length - 1].id : null;
|
||||
let worktree = null;
|
||||
try {
|
||||
const st = await run(repo.root, ['status', '--porcelain']);
|
||||
worktree = { files: st.split('\n').filter(Boolean).length };
|
||||
} catch (_) { worktree = null; }
|
||||
return { ok: true, repo, worktree, commits, next };
|
||||
}
|
||||
|
||||
async function commitDetail(dir, rev) {
|
||||
const repo = await ensureRepo(dir);
|
||||
if (rev === 'worktree') {
|
||||
const d = await worktreeDetail(repo.root);
|
||||
return { ok: true, repo, ...d };
|
||||
}
|
||||
let meta;
|
||||
try {
|
||||
meta = await run(repo.root, ['show', '-s', '--first-parent', '--format=%H%x1f%h%x1f%an%x1f%ae%x1f%aI%x1f%P%x1f%s%x1f%b', rev]);
|
||||
} catch (err) {
|
||||
throw Object.assign(new Error('提交不存在或读取失败'), { reason: 'bad_rev' });
|
||||
}
|
||||
const f = meta.split('\x1f');
|
||||
const commit = {
|
||||
id: f[0], short: f[1], author: f[2], email: f[3], time: f[4],
|
||||
parents: String(f[5] || '').split(' ').filter(Boolean),
|
||||
subject: f[6] || '', body: (f[7] || '').replace(/\s+$/, ''),
|
||||
};
|
||||
// --first-parent:合并提交默认不出 patch,跟第一个父提交比才是"这次合并带进来什么"
|
||||
let all = '';
|
||||
try { all = await run(repo.root, ['show', '--first-parent', '--format=', '--patch', rev]); } catch (_) { all = ''; }
|
||||
const map = splitPatch(all);
|
||||
const order = [...map.keys()];
|
||||
const files = buildFiles(map, order, null);
|
||||
return { ok: true, repo, kind: 'commit', commit, files, ...summarize(files) };
|
||||
}
|
||||
|
||||
// 统一入口:ok:false 只用于「不是仓库 / 没装 git / 会话不存在」,前端按 reason 出空状态
|
||||
async function query(dir, kind, opts) {
|
||||
try {
|
||||
if (kind === 'commits') return await listCommits(dir, opts && opts.before, opts && opts.limit);
|
||||
return await commitDetail(dir, (opts && opts.rev) || '');
|
||||
} catch (err) {
|
||||
return { ok: false, reason: (err && err.reason) || 'not_repo', error: String((err && err.message) || err) };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { query };
|
||||
+35
-15
@@ -58,6 +58,26 @@ function setProfilePrompts(map) {
|
||||
// system prompt 每次请求都随 messages 发出,拼接结果按 (profile, 语言) 缓存,不重复分配大字符串。
|
||||
let _promptTextCache = new Map(); // 'profile\u0000lang' -> text
|
||||
|
||||
// 部署形态决定的环境段:模板里的 {APP_ENV_SECTION} 由两份小模板填充(mode 由 server.js 启动时选定)。
|
||||
// 为什么不能写成一段「两边都成立」的话:服务器形态是容器(每会话隔离、会话级 /tmp、只读 skills),
|
||||
// 本地形态是用户自己那台机器(无沙箱、真实共享 /tmp)——两边的环境事实互相矛盾,混着写会误导模型。
|
||||
// 只选一次、进程内恒定,和技能段同属「前缀缓存不得抖动」的部分。
|
||||
const APP_ENV_TOKEN = '{APP_ENV_SECTION}';
|
||||
const ENV_TEXTS = {
|
||||
server: fs.readFileSync(path.join(__dirname, 'templates', 'env-server.txt'), 'utf8').trim(),
|
||||
local: fs.readFileSync(path.join(__dirname, 'templates', 'env-local.txt'), 'utf8').trim(),
|
||||
};
|
||||
let ENV_TEXT = ENV_TEXTS.server;
|
||||
function setEnvMode(mode) {
|
||||
ENV_TEXT = ENV_TEXTS[mode] || ENV_TEXTS.server;
|
||||
_promptTextCache = new Map(); // 环境段换了,拼接结果必须重建
|
||||
}
|
||||
|
||||
// 自定义 profile prompt 里写了占位符也照样生效(没写就是没有环境段,同技能段规则)。
|
||||
function withEnvSection(text) {
|
||||
return text.indexOf(APP_ENV_TOKEN) >= 0 ? text.split(APP_ENV_TOKEN).join(ENV_TEXT) : text;
|
||||
}
|
||||
|
||||
// “可用技能”段落(skills.formatSkillListForPrompt):启动时快照(server.js)与技能变更后
|
||||
//(routes/skills.js)经 setSkillListText 更新。插入位置由模板内的 {APP_SKILLS_SECTION} 占位符决定
|
||||
//(拼在技能规则旁边,模型一眼看到清单,不再盲猜尾部多出来的孤儿段落):
|
||||
@@ -85,12 +105,9 @@ function systemPromptText(language, profile) {
|
||||
const key = (profile || 'default') + '\u0000' + t;
|
||||
const hit = _promptTextCache.get(key);
|
||||
if (hit) return hit;
|
||||
let text;
|
||||
if (profile && PROFILE_PROMPTS[profile]) {
|
||||
text = withSkillList(PROFILE_PROMPTS[profile], false); // 自定义文件:没放占位符就真没有技能段
|
||||
} else {
|
||||
text = withSkillList(SYSTEM_PROMPT_TEMPLATE, true);
|
||||
}
|
||||
// 环境段先替(模板里的占位符),再拼技能段:自定义 prompt 没放占位符就真没有环境段/技能段
|
||||
const custom = profile && PROFILE_PROMPTS[profile];
|
||||
let text = withSkillList(withEnvSection(custom || SYSTEM_PROMPT_TEMPLATE), !custom);
|
||||
if (t) text += '\n\n## Reply Language\n' +
|
||||
'- ALWAYS respond to the user in ' + t + '. Tool descriptions, tool outputs and errors are usually in English — ' +
|
||||
'never let them switch your reply language. Tool names, parameters, code, file paths and shell commands stay as-is; ' +
|
||||
@@ -666,19 +683,22 @@ async function callModel(cfg, modelId, messages, tools, options) {
|
||||
if (opts.deepThink && modelCfg.thinking_params && Object.keys(modelCfg.thinking_params).length) {
|
||||
deepMergeInto(body, modelCfg.thinking_params);
|
||||
}
|
||||
// 思维链回传(逐模型 opt-in,纯配置闸门不看 tools):reasoning_ack_field 非空时,把
|
||||
// buildMessages 挂的内部键 __reasoning 按该字段名写回 assistant 行(对话/压缩/标题回合同规则;
|
||||
// 没配/无思考的行零变化)。无论配与否都剥一遍 __reasoning,内部键不出仓库。
|
||||
// 思维链回传(逐模型 opt-in):开思考时把 buildMessages 挂的内部键 __reasoning 按
|
||||
// reasoning_ack_field 写回 assistant 行;关思考时整段不发。带 tool_calls 的行缺思维链
|
||||
// 时用空串占位(缺失会被上游 400,空串实测通过)。__reasoning 是内部键,任何情况都剥。
|
||||
if (body.messages && body.messages.length) {
|
||||
const ack = modelCfg.reasoning_ack_field;
|
||||
// 思考模式下带 tool_calls 的 assistant 行必须回传 reasoning_content:中途开启思考时,
|
||||
// 本轮早先的调用没有思维链,用空串占位(缺失会被上游 400,空串实测通过)。
|
||||
const send = !!(ack && opts.deepThink);
|
||||
body.messages = body.messages.map(mm => {
|
||||
if (!mm || mm.role !== 'assistant') return mm;
|
||||
const fill = !!(opts.deepThink && ack && mm.tool_calls && !mm.__reasoning);
|
||||
if (!mm.__reasoning && !fill) return mm;
|
||||
if (!mm.__reasoning) {
|
||||
if (!send || !mm.tool_calls) return mm;
|
||||
const c = Object.assign({}, mm);
|
||||
c[ack] = '';
|
||||
return c;
|
||||
}
|
||||
const c = Object.assign({}, mm);
|
||||
if (ack) c[ack] = c.__reasoning || '';
|
||||
if (send) c[ack] = mm.__reasoning;
|
||||
delete c.__reasoning;
|
||||
return c;
|
||||
});
|
||||
@@ -795,4 +815,4 @@ async function callModel(cfg, modelId, messages, tools, options) {
|
||||
return { content, reasoning, tool_calls: Array.from(toolCalls.values()), finish_reason: finishReason, usage, aborted, sseFrames };
|
||||
}
|
||||
|
||||
module.exports = { callModel, buildMessages, buildSystemPrompt, systemPromptText, setSkillListText, setPayloadTrim, setProfilePrompts, encodeBlocks, decodeBlocks, compressMessages, titleMessages, patchImageReceipt };
|
||||
module.exports = { callModel, buildMessages, buildSystemPrompt, systemPromptText, setSkillListText, setEnvMode, setPayloadTrim, setProfilePrompts, encodeBlocks, decodeBlocks, compressMessages, titleMessages, patchImageReceipt };
|
||||
|
||||
+46
-7
@@ -118,7 +118,7 @@ function tokenScore(fl, t) {
|
||||
const frac = hit / (t.length - 1);
|
||||
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);
|
||||
if (!toks.length) return '';
|
||||
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);
|
||||
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 '';
|
||||
hits.sort((a, b) => b.score - a.score || a.i - b.i);
|
||||
const shown = hits.slice(0, lim);
|
||||
@@ -143,14 +160,36 @@ function searchFragments(db, user, query, count) {
|
||||
|
||||
// ---------- 读:日期索引 / 某天整天(只记得「大概哪天」时的翻页) ----------
|
||||
function daysIndex(db, user) {
|
||||
return db.prepare(
|
||||
'SELECT day, COUNT(*) n FROM memory_fragments WHERE user = ? GROUP BY day ORDER BY day DESC'
|
||||
).all(String(user || '')).map(r => '- ' + r.day + '(' + r.n + ' 条)');
|
||||
const u = String(user || '');
|
||||
const map = new Map();
|
||||
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) {
|
||||
return db.prepare(
|
||||
'SELECT ' + FRAG_COLS + FRAG_FROM + ' WHERE f.user = ? AND f.day = ? ORDER BY COALESCE(f.last_active_at, f.created_at)'
|
||||
).all(String(user || ''), String(date || '').trim()).map(renderFrag).join('\n\n');
|
||||
const u = String(user || '');
|
||||
const d = String(date || '').trim();
|
||||
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 ----------
|
||||
|
||||
+704
-146
File diff suppressed because it is too large
Load Diff
+177
-61
@@ -8,7 +8,21 @@
|
||||
<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>
|
||||
<script src="/vendor/marked.min.js"></script>
|
||||
<script src="/vendor/prism.min.js"></script>
|
||||
<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-status-bar-style" content="black-translucent">
|
||||
<meta name="apple-mobile-web-app-title" content="Agent">
|
||||
@@ -17,13 +31,12 @@
|
||||
<link rel="icon" type="image/png" sizes="192x192" href="/icons/icon-192.png">
|
||||
<link rel="stylesheet" href="/css/style.css">
|
||||
<style>
|
||||
/* 「压缩」摘要卡片:与 .msg-think 同族的折叠交互,但做成更醒目的蓝色调卡片;
|
||||
流式收尾(live)和历史重渲染(type='summary' 消息)共用同一套样式。
|
||||
live 阶段 open=true 展开阅读;历史重渲染默认收起。 */
|
||||
/* 「压缩」摘要卡片:与 .msg-ctx(画像快照/渠道/记忆)同一套视觉——淡蓝底、蓝边蓝字、
|
||||
三角箭头、虚线分隔。纯色不用渐变/阴影,折叠与展开同一底色。默认收起 */
|
||||
.msg-summary {
|
||||
margin: 0 0 8px; border: 1px solid #dbe4fb; border-radius: 12px; overflow: hidden;
|
||||
background: linear-gradient(180deg, #f7f9ff 0%, #ffffff 56%);
|
||||
box-shadow: 0 1px 3px rgba(57, 100, 254, 0.08);
|
||||
width: 100%; /* .msg.other 是 align-items:flex-start 的列 flex,不写就只撑标题那点宽 */
|
||||
margin: 0 0 8px; border: 1px solid var(--bd-dbe4fb); border-radius: 12px; overflow: hidden;
|
||||
background: var(--bg-f7f9ff);
|
||||
}
|
||||
.msg-summary > summary {
|
||||
list-style: none; cursor: pointer; user-select: none;
|
||||
@@ -37,13 +50,12 @@
|
||||
transition: transform .15s ease;
|
||||
}
|
||||
.msg-summary[open] > summary::before { transform: rotate(90deg); }
|
||||
.msg-summary .sum-ic { flex: none; width: 15px; height: 15px; }
|
||||
.msg-summary .sum-hint { margin-left: auto; font-size: 11px; font-weight: 400; color: var(--gray); }
|
||||
.msg-summary-body {
|
||||
border-top: 1px dashed #dbe4fb; background: var(--page);
|
||||
/* 比标题区深一档(用变量,暗色自动跟随) */
|
||||
border-top: 1px dashed var(--bd-dbe4fb); background: var(--bg-fbfcff);
|
||||
padding: 10px 13px 12px;
|
||||
}
|
||||
.msg-summary-body .bubble-ai { margin: 0; font-size: 14px; line-height: 1.7; }
|
||||
.msg-summary-body .bubble-ai { margin: 0; background: transparent; font-size: 14px; line-height: 1.7; }
|
||||
/* 「仅摘要」后摘要之前的旧历史:UI 保留但变淡,尾部附存档说明(不再发给 AI) */
|
||||
.msg-archived { opacity: .55; }
|
||||
.archived-note {
|
||||
@@ -57,7 +69,7 @@
|
||||
#schedule-modal .sched-row select,
|
||||
#schedule-modal .sched-row input {
|
||||
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 .sched-num { width: 52px; text-align: center; }
|
||||
@@ -66,9 +78,9 @@
|
||||
/* schedule 弹窗内的提示词编辑区(.modal input 不覆盖 textarea,单独给样式) */
|
||||
#schedule-modal textarea {
|
||||
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;
|
||||
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); }
|
||||
/* welcome 头像兼做「选择模型」入口(与聊天态的「选择模型」同一弹窗) */
|
||||
@@ -86,12 +98,79 @@
|
||||
</script>
|
||||
</head>
|
||||
<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">
|
||||
|
||||
<!-- ================= 顶部导航栏 ================= -->
|
||||
<header class="header" id="chat-header">
|
||||
<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>
|
||||
<div class="header-center" id="header-center"><!-- 未对话状态为空白,JS 注入对话信息 --></div>
|
||||
|
||||
@@ -102,11 +181,11 @@
|
||||
<span class="hdr-label" id="hdr-model-text">选择模型</span>
|
||||
</button>
|
||||
<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>
|
||||
</button>
|
||||
<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>
|
||||
</div>
|
||||
|
||||
@@ -114,28 +193,37 @@
|
||||
桌面属性区与菜单项共用 data-act,事件统一在 sessions.js 分发。 -->
|
||||
<div class="header-actions" id="header-actions">
|
||||
<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="新建会话">
|
||||
<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>
|
||||
</div>
|
||||
<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>
|
||||
<div class="ha-menu hidden" id="ha-menu" role="menu">
|
||||
<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>
|
||||
</button>
|
||||
<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>
|
||||
</button>
|
||||
<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>
|
||||
</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">
|
||||
<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>
|
||||
</button>
|
||||
</div>
|
||||
@@ -147,10 +235,22 @@
|
||||
<section id="welcome-view">
|
||||
<div class="welcome-head">
|
||||
<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 class="welcome-slogan">随时开始吧</div>
|
||||
</div>
|
||||
<!-- 本地端:新建会话时手选工作目录(服务器形态由 JS 整块隐藏)。
|
||||
只暂存在前端,真正建档时随 POST /api/sessions 提交一次;不选 = 老行为。 -->
|
||||
<div class="welcome-dir hidden" id="welcome-dir">
|
||||
<span class="welcome-dir-cap">工作目录</span>
|
||||
<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"><use href="#i-folder"/></svg>
|
||||
<span class="welcome-dir-path" id="welcome-dir-path">默认</span>
|
||||
</button>
|
||||
<button type="button" class="welcome-dir-clear hidden" id="welcome-dir-clear" title="恢复默认目录" aria-label="恢复默认目录">
|
||||
<svg class="ic sm" viewBox="0 0 24 24"><use href="#i-x-line"/></svg>
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- ================= 对话状态:对话内容区 ================= -->
|
||||
@@ -176,23 +276,23 @@
|
||||
<div class="input-actions">
|
||||
<div class="ia-side ia-left">
|
||||
<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>
|
||||
</div>
|
||||
<div class="ia-side ia-right">
|
||||
<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 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>
|
||||
<!-- 同一按钮四态:发送(↑)/ 停止(方块)/ 语音(麦克风)/ 键盘。
|
||||
data-state 由 JS 切换,尺寸不变避免输入区跳动 -->
|
||||
<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-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-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-send" viewBox="0 0 24 24"><use href="#i-send"/></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"><use href="#i-keyboard"/></svg>
|
||||
<span class="stop-sq" aria-hidden="true"></span>
|
||||
</button>
|
||||
</div>
|
||||
@@ -202,13 +302,18 @@
|
||||
<div id="voice-overlay" class="hidden" aria-hidden="true">
|
||||
<div class="vo-hint" id="voice-hint">松手传送,上滑取消</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>
|
||||
<!-- 回到底部浮动按钮(搬自 index;上翻历史时出现、AI 输出中常驻转圈)。
|
||||
放在 footer 内、相对 footer 顶边停靠:输入框长高/编辑条出现时不会被盖住 -->
|
||||
<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-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-arrow" viewBox="0 0 24 24"><use href="#i-chevron-down"/></svg>
|
||||
<svg class="sb-spinner hidden" viewBox="0 0 24 24"><use href="#i-spinner"/></svg>
|
||||
</button>
|
||||
</footer>
|
||||
|
||||
@@ -217,16 +322,21 @@
|
||||
<aside id="drawer" aria-label="对话历史">
|
||||
<div class="drawer-search">
|
||||
<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">
|
||||
</div>
|
||||
</div>
|
||||
<div class="drawer-list" id="drawer-list"></div>
|
||||
<div class="drawer-user" id="drawer-user">
|
||||
<div class="avatar" id="drawer-avatar">A</div>
|
||||
<div class="user-name" id="drawer-user-name">Agent 用户</div>
|
||||
<button class="user-more" id="user-more-btn" title="更多设置" aria-label="更多设置">
|
||||
<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>
|
||||
<div class="files-tree" id="files-tree"></div>
|
||||
<!-- 底部图标操作栏:文件树 / 设置(文件树按钮是「会话 ↔ 文件」的切换开关)。
|
||||
预览不占按钮:桌面端在文件树里点文件即开预览栏,关窗走预览栏自己的关闭钮。
|
||||
窄屏两个都隐藏:文件只保留输入行右侧的旧面板(不做两套)。选中项高亮。 -->
|
||||
<div class="drawer-actions" id="drawer-actions">
|
||||
<button class="drawer-act" id="da-files" type="button" title="文件树" aria-label="文件树">
|
||||
<svg viewBox="0 0 24 24"><use href="#i-folder"/></svg>
|
||||
</button>
|
||||
<button class="drawer-act" id="da-settings" type="button" title="设置" aria-label="设置">
|
||||
<svg viewBox="0 0 24 24"><use href="#i-gear"/></svg>
|
||||
</button>
|
||||
</div>
|
||||
</aside>
|
||||
@@ -239,7 +349,7 @@
|
||||
<span class="files-panel-title">任务文件<span class="files-panel-size" id="files-panel-size" title="当前目录下全部文件总大小"></span></span>
|
||||
<label class="file-upload" title="上传文件" aria-label="上传文件">
|
||||
<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>
|
||||
</div>
|
||||
<div class="files-crumbs hidden" id="files-crumbs" aria-label="目录路径"></div>
|
||||
@@ -255,10 +365,10 @@
|
||||
</div>
|
||||
<div class="files-panel-actions">
|
||||
<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 class="files-fab del" id="files-bulk-delete" title="批量删除" aria-label="批量删除" disabled>
|
||||
<svg viewBox="0 0 24 24"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"></path><line x1="10" y1="11" x2="10" y2="17"></line><line x1="14" y1="11" x2="14" y2="17"></line></svg>
|
||||
<svg viewBox="0 0 24 24"><use href="#i-trash"/></svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -273,7 +383,7 @@
|
||||
<!-- 顶栏:左侧返回 + 中间标题 + 右侧操作按钮,风格与对话页 header 一致 -->
|
||||
<header class="header">
|
||||
<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>
|
||||
<div class="header-center"><div class="header-title" id="set-title">设置</div></div>
|
||||
<div class="header-right" id="set-actions"><!-- JS 按页注入操作按钮 --></div>
|
||||
@@ -286,7 +396,7 @@
|
||||
<div id="skill-create-modal" class="modal-overlay hidden" onclick="if(event.target===this)sUI.closeCreate()">
|
||||
<div class="modal">
|
||||
<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>
|
||||
<h3>新建技能</h3>
|
||||
<input type="text" id="skill-new-name" placeholder="技能名(字母/数字/-/_)">
|
||||
@@ -299,7 +409,7 @@
|
||||
<div id="model-edit-modal" class="modal-overlay hidden" onclick="if(event.target===this)sUI.mClose()">
|
||||
<div class="modal modal-wide">
|
||||
<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>
|
||||
<h3 id="mpe-title">编辑平台</h3>
|
||||
<!-- 平台预设:仅新增平台时展示,点选即填好 url/类型并给模型卡带上该平台的参数缺省 -->
|
||||
@@ -325,7 +435,7 @@
|
||||
<div id="user-edit-modal" class="modal-overlay hidden" onclick="if(event.target===this)sUI.closeUserModal()">
|
||||
<div class="modal">
|
||||
<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>
|
||||
<h3 id="ue-title">添加用户</h3>
|
||||
<input type="text" id="ue-user" placeholder="用户名(字母/数字/下划线)" autocomplete="off">
|
||||
@@ -347,12 +457,12 @@
|
||||
<div id="mcp-edit-modal" class="modal-overlay hidden" onclick="if(event.target===this)mcpUI.close()">
|
||||
<div class="modal modal-wide">
|
||||
<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>
|
||||
<h3 id="mce-title">编辑 MCP 服务</h3>
|
||||
<input type="text" id="mce-name" placeholder="服务名">
|
||||
<input type="text" id="mce-url" placeholder="MCP 服务 JSON-RPC URL">
|
||||
<!-- 内置服务预设字段(url/name 只读,表单由预设生成) -->
|
||||
<!-- 内置服务预设字段(name 只读、url 可改,表单由预设生成) -->
|
||||
<div class="mpe-sec hidden" id="mce-preset-sec">
|
||||
<div class="mpe-sec-head"><span>配置参数</span><span class="cfg-note" id="mce-preset-desc"></span></div>
|
||||
<div id="mce-preset-fields"></div>
|
||||
@@ -385,7 +495,7 @@
|
||||
<div id="schedule-modal" class="modal-overlay hidden" onclick="if(event.target===this)closeScheduleModal()">
|
||||
<div class="modal">
|
||||
<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>
|
||||
<h3 id="schedule-modal-title">定时任务</h3>
|
||||
<div class="sched-row">
|
||||
@@ -418,7 +528,7 @@
|
||||
<div id="confirm-modal" class="modal-overlay hidden" onclick="if(event.target===this)confirmClose(null)">
|
||||
<div class="modal">
|
||||
<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>
|
||||
<h3 id="confirm-title">请确认</h3>
|
||||
<div class="modal-text" id="confirm-text"></div>
|
||||
@@ -434,7 +544,7 @@
|
||||
<div id="prompt-modal" class="modal-overlay hidden" onclick="if(event.target===this)promptCancel()">
|
||||
<div class="modal">
|
||||
<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>
|
||||
<h3 id="prompt-title">请输入</h3>
|
||||
<input type="text" id="prompt-input">
|
||||
@@ -454,7 +564,7 @@
|
||||
<p class="msw-sub" id="bind-model-sub">选择一个模型继续当前会话</p>
|
||||
</div>
|
||||
<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>
|
||||
</div>
|
||||
<div class="msw-list" id="bind-model-list"></div>
|
||||
@@ -472,26 +582,30 @@
|
||||
<span id="img-count" class="hidden"></span>
|
||||
</div>
|
||||
|
||||
<!-- ================= 文档预览右栏(桌面端≥960px;office/全部文档类型统一承载;移动端走全屏 #fs-viewer,本栏隐藏) -->
|
||||
<!-- ================= 文档预览分栏(桌面端≥960px;紧贴左侧文件树:文件树 | 预览 | 会话;office/全部文档类型统一承载;移动端走全屏 #fs-viewer,本栏隐藏) -->
|
||||
<aside id="pv-pane" aria-label="文档预览">
|
||||
<header class="pv-head">
|
||||
<!-- 地址条胶囊:路径 input(点击全选可复制) + 内嵌 刷新/新窗口,模拟浏览器地址栏 -->
|
||||
<span class="pv-addr">
|
||||
<input class="pv-title" id="pv-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 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>
|
||||
</span>
|
||||
<span class="pv-actions">
|
||||
<!-- 源码钮:只在当前内容有源文本时出现(md/文本/代码/html/svg),点了在预览与原文间切换 -->
|
||||
<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"><use href="#i-eye"/></svg>
|
||||
</button>
|
||||
<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 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 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" 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"><use href="#i-minimize"/></svg>
|
||||
</button>
|
||||
<button class="icon-btn" id="pv-close" title="关闭预览" aria-label="关闭预览">✕</button>
|
||||
</span>
|
||||
@@ -508,11 +622,11 @@
|
||||
<span class="fs-name" id="fs-file-name"></span>
|
||||
<!-- 源码切换钮:仅当当前内容有源文本时显隐(toggleFsSrc 在渲染视图/源码面板间互切) -->
|
||||
<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>
|
||||
<!-- 复制源码:显隐与 eye 一致(有源文本才出现);HTML/SVG/MD/代码通用 -->
|
||||
<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 class="fs-btn" onclick="closeFullscreen()" title="关闭" aria-label="关闭">✕</button>
|
||||
</div>
|
||||
@@ -523,7 +637,7 @@
|
||||
<!-- 拖拽上传提示层:window 级 dragenter 时显示;pointer-events:none,不参与命中测试(逻辑见 js/files.js) -->
|
||||
<div id="drop-overlay" class="hidden" aria-hidden="true">
|
||||
<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>
|
||||
</div>
|
||||
</div>
|
||||
@@ -536,17 +650,19 @@
|
||||
<script src="/js/files.js"></script>
|
||||
<script src="/js/voice.js"></script>
|
||||
<script src="/js/preview.js"></script>
|
||||
<script src="/js/vcs.js"></script>
|
||||
<script src="/js/files-tree.js"></script>
|
||||
<script src="/js/settings.js"></script>
|
||||
<script>
|
||||
// 启动自愈:外部工具改前端文件是非原子写入,极端时机下浏览器可能拿到半截或重复拼接的 HTML
|
||||
// (脚本缺半 → 白屏裸首页;重复注入 → 每个文件报 duplicate variable 后 JS 全挂)。
|
||||
// 这里检测关键脚本数量与入口全局,不对就自动整页重载一次(sessionStorage 防循环)。
|
||||
// 注意:js/ 脚本增减时需同步改这里的期望数 9。
|
||||
// 注意:js/ 脚本增减时需同步改这里的期望数 10。
|
||||
(function () {
|
||||
var ok = false;
|
||||
try {
|
||||
var n = document.querySelectorAll('script[src^="/js/"]').length;
|
||||
ok = n === 9 && typeof state !== 'undefined' &&
|
||||
ok = n === 10 && typeof state !== 'undefined' &&
|
||||
typeof openFilePreview === 'function' && typeof restartNow === 'function';
|
||||
} catch (_) {}
|
||||
if (ok) { try { sessionStorage.removeItem('boot-heal'); } catch (_) {} return; }
|
||||
|
||||
@@ -32,13 +32,13 @@
|
||||
// 删除本条:仅已落库消息可删(传 m.id);流式未落库时无 id,不渲染
|
||||
const del = 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>'
|
||||
: '';
|
||||
// 编辑并重发:只给未压缩的用户消息(调用方传 canEdit);带 b64 回填输入框,避免从 DOM 反推
|
||||
const edit = canEdit && msgId
|
||||
? '<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>'
|
||||
: '';
|
||||
const u = normUsage(usage);
|
||||
@@ -49,13 +49,28 @@
|
||||
'<span>' + fmtTime(ts) + '</span>' +
|
||||
usageHtml +
|
||||
'<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>' +
|
||||
edit +
|
||||
del +
|
||||
'</div>';
|
||||
}
|
||||
|
||||
// 上下文卡片:画像快照 / 渠道说明 / 开场记忆这类「只发给模型看的注入行」,
|
||||
// 统一渲染成可折叠的系统卡片,而不是伪装成用户发言。
|
||||
function ctxCardHtml(title, text, id) {
|
||||
const r = mdHtml(text || ''); // 与摘要卡片同样走 markdown,保持四张卡片观感一致
|
||||
return '<details class="msg-ctx"' + (id ? ' id="' + id + '"' : '') + '><summary>' + esc(title) + '</summary>'
|
||||
+ '<div class="msg-ctx-body"><div class="bubble-ai' + (r.fmt ? ' md' : '') + '">' + r.html + '</div></div></details>';
|
||||
}
|
||||
|
||||
// 画像快照是每轮请求拼在最前的上下文(不在 messages 表里)。历史是懒加载的,首屏只拉最近几条,
|
||||
// 所以不能一打开就插,得等翻到最早、确认没有更早的消息了再放到最顶。
|
||||
function ensureProfileCard(box) {
|
||||
if (!state.profileSnapshot || !box || box.querySelector('#ctx-profile')) return;
|
||||
box.insertAdjacentHTML('afterbegin', ctxCardHtml('画像快照', state.profileSnapshot, 'ctx-profile'));
|
||||
}
|
||||
|
||||
function userMsgHtml(m) {
|
||||
const p = parseUploadNotice(m.content);
|
||||
const attach = p.files && p.files.length
|
||||
@@ -72,16 +87,20 @@
|
||||
function aiMsgHtml(m) {
|
||||
const text = (m.content || '').trim();
|
||||
const reason = (m.reasoning || '').trim();
|
||||
if (!text && !reason) return null; // 纯工具调用的应答:不渲染气泡,工具卡由 appendToolCardsFromAssistant 铺
|
||||
const errAck = m.type === 'errAck';
|
||||
// 纯工具调用的应答不渲染气泡(工具卡由 appendToolCardsFromAssistant 铺),但 errAck 要留个标记
|
||||
if (!text && !reason && !errAck) return null;
|
||||
const note = errAck
|
||||
? '<div class="msg-note">工具调用参数无效,本轮已从上下文移除,模型会重新发起</div>' : '';
|
||||
const think = reason ? thinkPanelHtml(m.reasoning) : '';
|
||||
const bubble = text ? (() => { const r = mdHtml(m.content); return '<div class="bubble-ai' + (r.fmt ? ' md' : '') + '">' + r.html + '</div>'; })() : '';
|
||||
return '<div class="msg other">' + think + bubble + actionsHtml(m.created_at, m.content || '', m.id, m.usage) + '</div>';
|
||||
return '<div class="msg other">' + note + think + bubble + actionsHtml(m.created_at, m.content || '', m.id, m.usage) + '</div>';
|
||||
}
|
||||
// 思考过程折叠面板:summary 固定名「思考过程」+ 右侧复制按钮,body 展示推理全文。
|
||||
// 历史重渲染默认收起(与原设计一致),流式阶段的展开行为由 ensureStreamThinkPanel 显式控制。
|
||||
// 复制按钮走 onCopyClick 统一代理:点击时从 DOM 取思考全文(不依赖 b64,流式增量也能复制)
|
||||
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>';
|
||||
function thinkPanelHtml(text) {
|
||||
return '<details class="msg-think"><summary>思考过程' + THINK_COPY_BTN + '</summary><div class="msg-think-body">' + esc(text) + '</div></details>';
|
||||
@@ -93,7 +112,7 @@
|
||||
// 复制文本在点击时从 pre.textContent 现取(onCopyClick 的 .code-wrap 分支),不嵌 b64、不怕内容后续变化。
|
||||
// 只碰 .md 里的 pre:工具卡 / 思考区已有自己的复制按钮,行内 code 不加。
|
||||
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>';
|
||||
function decorateCodePre(root) {
|
||||
if (!root || !root.querySelectorAll) return;
|
||||
@@ -118,15 +137,7 @@
|
||||
|
||||
// 「压缩」摘要卡片:流式收尾与历史重渲染共用的头部(图标 + 标题 + 右侧说明)。
|
||||
function summaryHeaderHtml() {
|
||||
return '<summary>' +
|
||||
'<svg class="sum-ic" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round">' +
|
||||
'<ellipse cx="12" cy="5" rx="8" ry="2.5"></ellipse>' +
|
||||
'<path d="M4 5v6c0 1.4 3.6 2.5 8 2.5s8-1.1 8-2.5V5"></path>' +
|
||||
'<path d="M4 11v6c0 1.4 3.6 2.5 8 2.5s8-1.1 8-2.5v-6"></path>' +
|
||||
'</svg>' +
|
||||
'<span>上下文总结</span>' +
|
||||
'<span class="sum-hint">后续对话以此为起点</span>' +
|
||||
'</summary>';
|
||||
return '<summary><span>上下文总结</span></summary>';
|
||||
}
|
||||
|
||||
// 历史重渲染:被标记 type='summary' 的摘要消息渲染成摘要卡片(默认收起,点开可重现)。
|
||||
@@ -161,14 +172,14 @@
|
||||
if (!text) return '';
|
||||
const b64 = btoa(unescape(encodeURIComponent(text)));
|
||||
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 里的调用同步摘除。
|
||||
// msgId = tool 消息的库行 id(历史渲染传 m.id;实时由 tool_result 事件的 msg_id 携带)
|
||||
function toolDelBtnHtml(msgId) {
|
||||
if (!msgId) return '';
|
||||
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) {
|
||||
const div = document.createElement('div');
|
||||
@@ -322,7 +333,11 @@
|
||||
}
|
||||
|
||||
function msgNode(m) {
|
||||
if (m.role === 'user') return userMsgHtml(m);
|
||||
if (m.role === 'user') {
|
||||
if (m.type === 'channel_note') return ctxCardHtml('渠道上下文', m.content);
|
||||
if (m.type === 'memory_note') return ctxCardHtml('开场记忆', m.content);
|
||||
return userMsgHtml(m);
|
||||
}
|
||||
// 被「压缩总结」标记的摘要消息:重渲染成摘要卡片,而不是普通 AI 气泡
|
||||
if (m.role === 'assistant') return m.type === 'summary' ? summaryMsgHtml(m) : aiMsgHtml(m);
|
||||
return null; // tool 结果不单独展示
|
||||
@@ -365,6 +380,7 @@
|
||||
}
|
||||
// 历史渲染收口:给本轮新渲染出的代码块补复制按钮(目标可能是分页离屏容器,装饰后再随节点搬迁)
|
||||
decorateCodePre(target);
|
||||
pvHighlightMdCode(target); // 对话正文里的围栏代码块也上色(与预览同一套)
|
||||
return { closeArc };
|
||||
}
|
||||
|
||||
@@ -431,9 +447,12 @@
|
||||
const prevTop = keepView ? box.scrollTop : 0;
|
||||
const followBottom = !keepView || !box.firstElementChild || isNearBottom();
|
||||
box.innerHTML = '';
|
||||
state.profileSnapshot = (s && s.profile_snapshot) || '';
|
||||
appendMessagesDom(detail.messages || [], box).closeArc();
|
||||
// 首屏就把历史拉完了(条数少):直接上画像卡片;否则等上滑翻到最早再插
|
||||
if (!detail.has_more) ensureProfileCard(box);
|
||||
if (!(detail.messages || []).length) {
|
||||
box.innerHTML = '<div class="drawer-empty">描述你的需求,AI 会和你讨论并直接干活。</div>';
|
||||
box.insertAdjacentHTML('beforeend', '<div class="drawer-empty">描述你的需求,AI 会和你讨论并直接干活。</div>');
|
||||
}
|
||||
state.chatHasMore = !!detail.has_more;
|
||||
state.chatOldestId = detail.oldest_id || null;
|
||||
@@ -501,6 +520,7 @@
|
||||
while (frag.firstChild) box.insertBefore(frag.firstChild, anchor);
|
||||
box.scrollTop = box.scrollHeight - prevH + prevTop;
|
||||
state.chatHasMore = !!detail.has_more;
|
||||
if (!detail.has_more) ensureProfileCard(box); // 翻到最早了:画像卡片补到流最顶
|
||||
if (detail.oldest_id) state.chatOldestId = detail.oldest_id;
|
||||
state.chatLoadedCount += (detail.messages || []).length;
|
||||
// 旧页太短导致补完后仍贴在触发区:继续拉下一页,避免卡在顶部要再动一下才加载
|
||||
|
||||
@@ -148,11 +148,11 @@
|
||||
const MODES = {
|
||||
secretary: {
|
||||
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: {
|
||||
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>',
|
||||
},
|
||||
};
|
||||
|
||||
@@ -161,7 +161,7 @@
|
||||
view: 'welcome', // welcome | chat
|
||||
mode: 'secretary', // 新建会话默认助手类型(欢迎页已去掉模式切换,不再可变)
|
||||
sessionType: 'secretary', // 当前会话的助手类型(建档时锁定,后续不随模式切换变更)
|
||||
deepThink: false, // 深度思考开关(仅本地视觉状态,无后端参数)
|
||||
deepThink: false, // 深度思考开关(发消息时落库到 sessions.deep_think,重进会话回填)
|
||||
pendingModel: '', // welcome 预选模型(ensureSession 建档时透传 model_id)
|
||||
sessionId: null, // 当前会话
|
||||
sessionTitle: '', // 当前会话标题
|
||||
@@ -208,7 +208,11 @@
|
||||
function renderHeader() {
|
||||
const c = $('header-center');
|
||||
// welcome(含刚 newChat)一律清空:newChat 会停在 welcome,不重刷会残留旧会话标题
|
||||
if (state.view !== 'chat' || !state.sessionId) { c.innerHTML = ''; return; }
|
||||
if (state.view !== 'chat' || !state.sessionId) {
|
||||
c.innerHTML = '';
|
||||
document.title = 'Agent 任务台'; // 回欢迎页/新建会话时标签页恢复默认
|
||||
return;
|
||||
}
|
||||
// 顶部只显标题;助手类型 icon 早已退位(会话阶段徽标随 advising 一并移除)
|
||||
const title = document.createElement('div');
|
||||
title.className = 'header-title';
|
||||
@@ -218,6 +222,8 @@
|
||||
title.addEventListener('click', renameSession); // 点标题重命名(同步 index)
|
||||
c.innerHTML = '';
|
||||
c.appendChild(title);
|
||||
// 标签页标题跟着会话走:切会话/重命名/自动生成标题都会走到这里
|
||||
document.title = state.sessionTitle || 'Agent 任务台';
|
||||
}
|
||||
|
||||
// ---------- 模式切换已移除:新建会话固定用 state.mode(secretary),助手类型不再占顶部 icon
|
||||
|
||||
@@ -0,0 +1,539 @@
|
||||
// 桌面端左栏文件树:会话文件的唯一浏览入口(服务器形态与 local 形态共用)。
|
||||
// · 懒加载:一次只请求一层目录,展开才拉下一层;node_modules 这类大目录后端只回标记、不展开,
|
||||
// 避免旧的整棵递归接口在单线程 core 上卡死;
|
||||
// · 点文件 → 中间预览栏(文件树 | 预览 | 会话);行内 hover 出「下载 / 删除 / 在 Finder 中显示」;
|
||||
// · 「在 Finder / 终端中打开」只在 local 启动器下可用(服务器上这些动作没有意义),
|
||||
// 靠 /api/local/info 探测,拿不到就隐藏这两个按钮。
|
||||
// 手机端不启用(收纳在抽屉里体验太差),仍走输入行右侧的旧文件面板。
|
||||
// 依赖(全局):state $ req toast downloadFile confirmModal openFilePreview
|
||||
'use strict';
|
||||
(function () {
|
||||
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"><use href="#i-file"/></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"><use href="#i-external-b"/></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"><use href="#i-terminal"/></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"><use href="#i-eye-sm"/></svg>';
|
||||
const SVG_DL = '<svg viewBox="0 0 24 24"><use href="#i-download"/></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"><use href="#i-external-b"/></svg>';
|
||||
const SVG_AT = '<span class="at-glyph">@</span>';
|
||||
|
||||
let localCapable = false; // local 启动器:才显示「在 Finder/终端中打开」
|
||||
let showHidden = false;
|
||||
let expanded = new Set(['']); // 已展开的相对目录('' = 根)
|
||||
let cache = new Map(); // rel -> /tree 响应
|
||||
let loading = new Map(); // rel -> Promise(并发去重)
|
||||
let emptyDirs = new Map(); // rel -> 目录 mtimeMs:确认空着的目录,mtime 没变就不必再请求
|
||||
let gen = 0; // 会话切换/刷新时自增,防止旧请求回填到新树的缓存
|
||||
// 多选:rel -> 'dir' | 'file'。勾目录表示整个目录(下载打成一个 zip、删除递归),
|
||||
// 所以勾目录会吃掉子项,勾子项会把祖先目录降级掉,见 toggleSel。
|
||||
let sel = new Map();
|
||||
|
||||
// 失效缓存。gen 自增让在飞的旧请求回来时不再写缓存(否则切会话会闪旧目录)。
|
||||
function invalidate(keepExpanded) {
|
||||
gen++;
|
||||
cache = new Map();
|
||||
loading = new Map();
|
||||
if (!keepExpanded) { expanded = new Set(['']); sel.clear(); emptyDirs = new Map(); }
|
||||
}
|
||||
|
||||
function sid() { return (state && state.sessionId) || ''; }
|
||||
|
||||
function tip(parent, text, cls) {
|
||||
const el = document.createElement('div');
|
||||
el.className = cls || 'tree-empty';
|
||||
el.textContent = text;
|
||||
parent.appendChild(el);
|
||||
}
|
||||
|
||||
function openDir(rel, dirMtime) {
|
||||
if (cache.has(rel)) return Promise.resolve(cache.get(rel));
|
||||
if (loading.has(rel)) return loading.get(rel);
|
||||
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=' +
|
||||
encodeURIComponent(rel) + (showHidden ? '&hidden=1' : '');
|
||||
const myGen = gen;
|
||||
const p = req('GET', url).then(function (data) {
|
||||
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;
|
||||
}, function (e) {
|
||||
if (myGen === gen) loading.delete(rel);
|
||||
throw e;
|
||||
});
|
||||
loading.set(rel, p);
|
||||
return p;
|
||||
}
|
||||
|
||||
function actBtn(act, title, svg, danger) {
|
||||
const b = document.createElement('button');
|
||||
b.type = 'button';
|
||||
b.className = 'tree-act' + (danger ? ' danger' : '');
|
||||
b.dataset.act = act;
|
||||
b.title = title;
|
||||
b.innerHTML = svg;
|
||||
return b;
|
||||
}
|
||||
|
||||
function rowFor(ent, depth) {
|
||||
const row = document.createElement('div');
|
||||
row.className = 'tree-row';
|
||||
row.dataset.rel = ent.rel;
|
||||
row.dataset.type = ent.type;
|
||||
row.style.paddingLeft = (6 + depth * 14) + 'px';
|
||||
row.title = ent.rel;
|
||||
if (ent.type === 'dir') {
|
||||
row.classList.add('is-dir');
|
||||
if (expanded.has(ent.rel)) row.classList.add('open');
|
||||
}
|
||||
if (ent.type === 'link') row.classList.add('is-link');
|
||||
if (ent.ignored) row.classList.add('is-ignored');
|
||||
|
||||
// 不画展开箭头:文件夹图标已经说明可以点,点行任意位置都能展开/收起。
|
||||
|
||||
// 勾选框:hover 或已选中时淡入,但占位始终在,避免 hover 时文件名左右跳。
|
||||
// 忽略的大目录和软链不参与批量操作(后端也不让删),所以不给勾选框。
|
||||
if (!ent.ignored && ent.type !== 'link') {
|
||||
const chk = document.createElement('span');
|
||||
chk.className = 'tree-check';
|
||||
chk.setAttribute('role', 'checkbox');
|
||||
chk.setAttribute('aria-label', '选择');
|
||||
const on = sel.has(ent.rel);
|
||||
chk.setAttribute('aria-checked', on ? 'true' : 'false');
|
||||
if (on) row.classList.add('selected');
|
||||
row.appendChild(chk);
|
||||
}
|
||||
|
||||
const ico = document.createElement('span');
|
||||
ico.className = 'tree-ico';
|
||||
ico.innerHTML = ent.type === 'dir' ? SVG_FOLDER : (ent.type === 'link' ? SVG_LINK : SVG_FILE);
|
||||
row.appendChild(ico);
|
||||
|
||||
const name = document.createElement('span');
|
||||
name.className = 'tree-name';
|
||||
name.textContent = ent.name;
|
||||
row.appendChild(name);
|
||||
|
||||
if (ent.ignored) {
|
||||
row.title = ent.rel + '(已忽略的大目录/构建产物)';
|
||||
return row;
|
||||
}
|
||||
// 行内动作:服务器形态给「下载 / 删除」;local 本就跑在同一台机器上,
|
||||
// 「下载」到本地是多余的(用 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 (localCapable) row.appendChild(actBtn('reveal', '在 Finder 中显示', SVG_REVEAL_SM, false));
|
||||
row.appendChild(actBtn('delete', '删除', SVG_DEL, true));
|
||||
return row;
|
||||
}
|
||||
|
||||
async function renderDirInto(container, rel, depth, dirMtime) {
|
||||
container.innerHTML = '';
|
||||
const data = await openDir(rel, dirMtime);
|
||||
if (!data) return;
|
||||
const frag = document.createDocumentFragment();
|
||||
const list = data.entries || [];
|
||||
// 只在根目录给空提示:子目录展开后本来就该「看不出变化」,根节点全空白则分不清是空还是没加载
|
||||
if (!list.length && !rel) tip(frag, '(空目录)');
|
||||
for (const ent of list) {
|
||||
frag.appendChild(rowFor(ent, depth));
|
||||
if (ent.type === 'dir' && !ent.ignored && expanded.has(ent.rel)) {
|
||||
const kids = document.createElement('div');
|
||||
kids.className = 'tree-children';
|
||||
frag.appendChild(kids);
|
||||
renderDirInto(kids, ent.rel, depth + 1, ent.mtimeMs).catch(function () {}); // 异步填充子层
|
||||
}
|
||||
}
|
||||
if (data.capped) tip(frag, '仅显示前 ' + list.length + ' 项(共 ' + data.total + ' 项)', 'tree-more');
|
||||
container.appendChild(frag);
|
||||
}
|
||||
|
||||
async function renderBody() {
|
||||
const body = $('tree-body');
|
||||
if (!body) return;
|
||||
// 没有会话就没有任务目录:不写提示,直接把侧栏退回会话列表。
|
||||
// 这条会兜住「在文件页里点了新建会话 / 删掉了当前会话」——那时卡片不该停在一个空树里。
|
||||
if (!sid()) {
|
||||
body.innerHTML = '';
|
||||
if (typeof setDrawerPane === 'function') setDrawerPane(false);
|
||||
return;
|
||||
}
|
||||
const sc = body.scrollTop;
|
||||
body.innerHTML = '';
|
||||
const root = document.createElement('div');
|
||||
body.appendChild(root);
|
||||
try {
|
||||
await renderDirInto(root, '', 0);
|
||||
} catch (e) {
|
||||
root.innerHTML = '';
|
||||
tip(root, '加载失败:' + e.message);
|
||||
}
|
||||
body.scrollTop = sc;
|
||||
syncSelUI();
|
||||
}
|
||||
|
||||
async function localAction(kind, rel) {
|
||||
if (!localCapable) return;
|
||||
if (!sid()) { toast('尚未开始会话'); return; }
|
||||
try {
|
||||
await req('POST', '/api/local/' + kind, { session: sid(), path: rel });
|
||||
} catch (e) {
|
||||
toast((kind === 'reveal' ? '打开目录失败:' : '打开终端失败:') + e.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteNode(rel, isDir) {
|
||||
if (!sid()) return;
|
||||
const name = rel.split('/').pop();
|
||||
const ok = typeof confirmModal === 'function'
|
||||
? await confirmModal('删除' + (isDir ? '文件夹' : '文件'),
|
||||
'删除「' + name + '」' + (isDir ? '(含其中全部内容)' : '') + '?', '删除', true)
|
||||
: true;
|
||||
if (!ok) return;
|
||||
try {
|
||||
await req('DELETE', '/api/sessions/' + sid() + '/files?path=' + encodeURIComponent(rel));
|
||||
// 预览里正开着被删的文件 → 一起关掉,别留一份已不存在的内容
|
||||
if (typeof pvState === 'object' && pvState && pvState.name === rel && typeof pvCloseDoc === 'function') pvCloseDoc();
|
||||
sel.delete(rel);
|
||||
invalidate(true);
|
||||
renderBody();
|
||||
} catch (e) { toast('删除失败:' + e.message); }
|
||||
}
|
||||
|
||||
// ---- 多选与批量操作 ----
|
||||
|
||||
// 有效选中:自身被勾,或某个祖先目录被勾(勾目录=整目录)。
|
||||
// 注意 UI 上只给 sel 里显式存在的行打勾:目录打勾就代表整目录,子行不再重复显示勾。
|
||||
function isSel(rel) {
|
||||
if (sel.has(rel)) return true;
|
||||
let p = rel;
|
||||
while (p.lastIndexOf('/') > 0) {
|
||||
p = p.slice(0, p.lastIndexOf('/'));
|
||||
if (sel.has(p)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function toggleSel(rel, type) {
|
||||
if (sel.has(rel)) {
|
||||
sel.delete(rel);
|
||||
} else {
|
||||
// 选子项时祖先目录降级为部分选择,否则一个目录会既「全选」又「只选一部分」
|
||||
let p = rel;
|
||||
while (p.lastIndexOf('/') > 0) {
|
||||
p = p.slice(0, p.lastIndexOf('/'));
|
||||
sel.delete(p);
|
||||
}
|
||||
sel.set(rel, type);
|
||||
}
|
||||
syncSelUI();
|
||||
}
|
||||
|
||||
// 当前可见(已展开)的可选行
|
||||
function visibleRows() {
|
||||
const body = $('tree-body');
|
||||
if (!body) return [];
|
||||
return Array.from(body.querySelectorAll('.tree-row')).filter(function (r) {
|
||||
return !r.classList.contains('is-ignored') && r.dataset.type !== 'link';
|
||||
});
|
||||
}
|
||||
|
||||
// 提交给后端前折叠:目录已选时,它下面的路径不再单独出现(否则 zip 里会重复)
|
||||
function effectiveSel() {
|
||||
const keys = Array.from(sel.keys()).sort(function (a, b) {
|
||||
return a.split('/').length - b.split('/').length;
|
||||
});
|
||||
const out = [];
|
||||
for (const k of keys) {
|
||||
if (!out.some(function (p) { return k.startsWith(p + '/'); })) out.push(k);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function syncSelUI() {
|
||||
const body = $('tree-body');
|
||||
if (body) {
|
||||
body.querySelectorAll('.tree-row').forEach(function (row) {
|
||||
const chk = row.querySelector('.tree-check');
|
||||
if (!chk) return;
|
||||
const on = sel.has(row.dataset.rel);
|
||||
chk.setAttribute('aria-checked', on ? 'true' : 'false');
|
||||
row.classList.toggle('selected', on);
|
||||
});
|
||||
}
|
||||
const n = sel.size;
|
||||
const cnt = $('tree-sel-count'), dl = $('tree-bulk-download'), del = $('tree-bulk-delete');
|
||||
if (cnt) cnt.textContent = n ? '已选 ' + n + ' 项' : '未选择';
|
||||
if (dl) dl.disabled = !n;
|
||||
if (del) del.disabled = !n;
|
||||
const all = $('tree-check-all');
|
||||
if (all) {
|
||||
const rows = visibleRows();
|
||||
const every = rows.length > 0 && rows.every(function (r) { return isSel(r.dataset.rel); });
|
||||
all.setAttribute('aria-checked', every ? 'true' : (n ? 'mixed' : 'false'));
|
||||
}
|
||||
}
|
||||
|
||||
function toggleSelAll() {
|
||||
const rows = visibleRows();
|
||||
const every = rows.length > 0 && rows.every(function (r) { return isSel(r.dataset.rel); });
|
||||
sel.clear();
|
||||
if (!every) {
|
||||
// 浅的先加:父目录已经覆盖的子项不再重复记
|
||||
rows.map(function (r) { return [r.dataset.rel, r.dataset.type]; })
|
||||
.sort(function (a, b) { return a[0].split('/').length - b[0].split('/').length; })
|
||||
.forEach(function (it) { if (!isSel(it[0])) sel.set(it[0], it[1]); });
|
||||
}
|
||||
syncSelUI();
|
||||
}
|
||||
|
||||
async function bulkDownload() {
|
||||
if (!sid() || !sel.size) return;
|
||||
const paths = effectiveSel();
|
||||
const hasDir = paths.some(function (p) { return sel.get(p) === 'dir'; });
|
||||
// 含目录 → 后端打成一个 zip;纯文件 → 逐个签名直链。
|
||||
// 先把 token 全取完再逐个触发,边取边点会让浏览器把后面的当弹窗拦掉。
|
||||
if (hasDir) {
|
||||
try {
|
||||
const r = await req('GET', '/api/sessions/' + sid() + '/files/zip-token?paths=' +
|
||||
encodeURIComponent(JSON.stringify(paths)));
|
||||
if (!r || !r.url) throw new Error('未拿到打包链接');
|
||||
const a = document.createElement('a');
|
||||
a.href = r.url;
|
||||
if (r.name) a.download = r.name;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
} catch (e) { toast('打包下载失败:' + e.message); }
|
||||
return;
|
||||
}
|
||||
const items = [];
|
||||
for (const p of paths) {
|
||||
try {
|
||||
const r = await req('GET', '/api/sessions/' + sid() + '/files/download-token?path=' +
|
||||
encodeURIComponent(p));
|
||||
if (r && r.url) items.push({ name: p.split('/').pop(), url: r.url });
|
||||
} catch (e) { /* 单个取票失败不拖累其余 */ }
|
||||
}
|
||||
if (!items.length) { toast('下载失败'); return; }
|
||||
items.forEach(function (it, i) {
|
||||
setTimeout(function () {
|
||||
const a = document.createElement('a');
|
||||
a.href = it.url;
|
||||
a.download = it.name;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
}, i * 250);
|
||||
});
|
||||
}
|
||||
|
||||
async function bulkDelete() {
|
||||
if (!sid() || !sel.size) return;
|
||||
const paths = effectiveSel();
|
||||
const ok = typeof confirmModal === 'function'
|
||||
? await confirmModal('批量删除', '删除选中的 ' + paths.length + ' 项?文件夹会连同内容一起删除。', '删除', true)
|
||||
: true;
|
||||
if (!ok) return;
|
||||
let done = 0, fail = 0;
|
||||
for (const p of paths) {
|
||||
try {
|
||||
await req('DELETE', '/api/sessions/' + sid() + '/files?path=' + encodeURIComponent(p));
|
||||
done++;
|
||||
} catch (e) { fail++; }
|
||||
}
|
||||
// 预览里正开着被删的文件就一起关掉,别留一份已不存在的内容
|
||||
if (typeof pvState === 'object' && pvState && pvState.name && typeof pvCloseDoc === 'function') {
|
||||
const cur = pvState.name;
|
||||
if (paths.some(function (p) { return cur === p || cur.startsWith(p + '/'); })) pvCloseDoc();
|
||||
}
|
||||
sel.clear();
|
||||
invalidate(true);
|
||||
renderBody();
|
||||
if (fail) toast('已删除 ' + done + ' 项,' + fail + ' 项失败'); // 全成功时列表自己就空了,不弹
|
||||
}
|
||||
|
||||
function onTreeClick(e) {
|
||||
const row = e.target.closest('.tree-row');
|
||||
if (!row) return;
|
||||
const rel = row.dataset.rel;
|
||||
const isDir = row.dataset.type === 'dir';
|
||||
// 勾选框只切换选中,不展开、不预览(树里点错行代价大,整行不承担选中)
|
||||
if (e.target.closest('.tree-check')) {
|
||||
e.stopPropagation();
|
||||
toggleSel(rel, row.dataset.type);
|
||||
return;
|
||||
}
|
||||
const act = e.target.closest('.tree-act');
|
||||
if (act) {
|
||||
e.stopPropagation();
|
||||
const a = act.dataset.act;
|
||||
if (a === 'download') { if (typeof downloadFile === 'function') downloadFile(rel); }
|
||||
else if (a === 'delete') deleteNode(rel, isDir);
|
||||
else if (a === 'reveal') localAction('reveal', rel);
|
||||
else if (a === 'at') insertPathRef(rel, isDir);
|
||||
return;
|
||||
}
|
||||
if (row.classList.contains('is-ignored') || row.dataset.type === 'link') return;
|
||||
if (isDir) {
|
||||
if (expanded.has(rel)) expanded.delete(rel); else expanded.add(rel);
|
||||
renderBody();
|
||||
} else if (typeof openFilePreview === 'function') {
|
||||
openFilePreview(rel, '');
|
||||
// 窄屏的预览是全屏浮层:点完把抽屉收起(同点会话的行为),否则关预览后还压在抽屉上
|
||||
if (typeof openDrawer === 'function' && !window.matchMedia('(min-width: 960px)').matches) openDrawer(false);
|
||||
}
|
||||
}
|
||||
|
||||
// @ 引用:把相对路径插到对话框光标处。插的是纯相对路径,不带 @ 前缀——
|
||||
// @<会话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/终端中打开」露出来(服务器形态永远隐藏)
|
||||
|
||||
function syncLocalButtons() {
|
||||
const rv = $('tree-reveal'), tm = $('tree-terminal');
|
||||
if (rv) rv.classList.toggle('hidden', !localCapable);
|
||||
if (tm) tm.classList.toggle('hidden', !localCapable);
|
||||
// 本地端文件就在本机,批量下载是多余的,底栏只留删除;服务器端才需要
|
||||
const bulkDl = $('tree-bulk-download');
|
||||
if (bulkDl) bulkDl.classList.toggle('hidden', localCapable);
|
||||
if (localCapable && $('tree-body')) renderBody(); // 行内 reveal 按钮也要重新生成
|
||||
}
|
||||
|
||||
function ensureShell() {
|
||||
const box = $('files-tree');
|
||||
if (!box || box.dataset.ready) return;
|
||||
box.dataset.ready = '1';
|
||||
box.innerHTML = '';
|
||||
|
||||
// 头部直接复用预览栏的 .pv-head / .pv-actions / .icon-btn:
|
||||
// 两者在桌面上左右并排,尺寸/描边/内边距必须一模一样,否则一眼就看出错位。
|
||||
// 不放地址条(路径在 280px 里必然截断,没有信息量)。
|
||||
// 操作钮按用途分两组:左边是树内的只读操作(显示隐藏文件 / 刷新 / Git 面板),
|
||||
// 右边是拉到外部打开(Finder / 终端,仅本地模式出现)。两组分居两端,连点不易误触。
|
||||
const head = document.createElement('header');
|
||||
head.className = 'pv-head tree-head';
|
||||
head.innerHTML =
|
||||
'<span class="pv-actions tree-actions-main">' +
|
||||
'<button class="icon-btn" type="button" id="tree-hidden" title="显示隐藏文件" aria-label="显示隐藏文件">' + SVG_EYE + '</button>' +
|
||||
'<button class="icon-btn" type="button" id="tree-refresh" title="刷新" aria-label="刷新">' + SVG_REFRESH + '</button>' +
|
||||
'<button class="icon-btn" type="button" id="tree-vcs" title="Git 改动与历史" aria-label="Git 改动与历史">' + SVG_VCS + '</button>' +
|
||||
'</span>' +
|
||||
'<span class="pv-actions tree-actions-ext">' +
|
||||
'<button class="icon-btn hidden" type="button" id="tree-reveal" title="在 Finder 中打开" aria-label="在 Finder 中打开">' + SVG_REVEAL + '</button>' +
|
||||
'<button class="icon-btn hidden" type="button" id="tree-terminal" title="在终端中打开" aria-label="在终端中打开">' + SVG_TERM + '</button>' +
|
||||
'</span>';
|
||||
|
||||
const body = document.createElement('div');
|
||||
body.className = 'tree-body';
|
||||
body.id = 'tree-body';
|
||||
|
||||
// 底部批量条:全选框、计数、下载/删除。未选时两个按钮禁用。
|
||||
const foot = document.createElement('div');
|
||||
foot.className = 'tree-foot';
|
||||
foot.innerHTML =
|
||||
'<span class="tree-check-all" id="tree-check-all" role="checkbox" aria-checked="false" title="全选当前可见" aria-label="全选"></span>' +
|
||||
'<span class="tree-sel-count" id="tree-sel-count">未选择</span>' +
|
||||
'<button class="tree-foot-btn" type="button" id="tree-bulk-download" title="下载所选" aria-label="下载所选" disabled>' + SVG_DL + '</button>' +
|
||||
'<button class="tree-foot-btn danger" type="button" id="tree-bulk-delete" title="删除所选" aria-label="删除所选" disabled>' + SVG_DEL + '</button>';
|
||||
|
||||
box.appendChild(head);
|
||||
box.appendChild(body);
|
||||
box.appendChild(foot);
|
||||
|
||||
head.querySelector('#tree-hidden').addEventListener('click', function () {
|
||||
showHidden = !showHidden;
|
||||
invalidate(false);
|
||||
this.classList.toggle('active', showHidden);
|
||||
renderBody();
|
||||
});
|
||||
head.querySelector('#tree-refresh').addEventListener('click', function () {
|
||||
invalidate(true);
|
||||
renderBody();
|
||||
});
|
||||
head.querySelector('#tree-reveal').addEventListener('click', function () { localAction('reveal', ''); });
|
||||
head.querySelector('#tree-terminal').addEventListener('click', function () { localAction('terminal', ''); });
|
||||
head.querySelector('#tree-vcs').addEventListener('click', function () {
|
||||
if (typeof window.openVcsPane === 'function') window.openVcsPane();
|
||||
});
|
||||
foot.querySelector('#tree-check-all').addEventListener('click', toggleSelAll);
|
||||
foot.querySelector('#tree-bulk-download').addEventListener('click', bulkDownload);
|
||||
foot.querySelector('#tree-bulk-delete').addEventListener('click', bulkDelete);
|
||||
body.addEventListener('click', onTreeClick);
|
||||
|
||||
syncLocalButtons();
|
||||
}
|
||||
|
||||
// 侧栏底部「文件树」图标 → 切到这个面板(由 files.js 的 setDrawerPane 调用)。
|
||||
window.showFileTree = function () {
|
||||
ensureShell();
|
||||
invalidate(true); // 切回面板一律重拉已展开的目录,不拿上次的缓存糊弄(后台只标脏的也在这里补上)
|
||||
renderBody();
|
||||
};
|
||||
|
||||
// 会话切换后由 sessions.js 调用,避免树停在旧会话。
|
||||
window.refreshFileTree = function () {
|
||||
invalidate(false);
|
||||
const drawer = $('drawer');
|
||||
if (drawer && drawer.classList.contains('drawer-mode-files')) renderBody();
|
||||
};
|
||||
|
||||
// 按需刷新(一轮跑完 / 回前台 / 断线重连):保留展开与勾选,只重拉已展开的目录。
|
||||
// 不在文件树面板时只标脏不渲染,等切回来由 showFileTree 重新拉。
|
||||
let reloadTimer = 0, reloadAt = 0, reloading = false;
|
||||
window.reloadFileTree = function () {
|
||||
clearTimeout(reloadTimer);
|
||||
reloadTimer = setTimeout(async function () {
|
||||
if (Date.now() - reloadAt < 1000) return; // 刚刷过:多路触发(done/visibility/focus/resync)合并掉
|
||||
if (reloading) return; // 上一轮还在渲,跳过(它读到的就是刚清过的缓存)
|
||||
reloadAt = Date.now();
|
||||
invalidate(true);
|
||||
const drawer = $('drawer');
|
||||
if (!drawer || !drawer.classList.contains('drawer-mode-files')) return;
|
||||
reloading = true;
|
||||
try { await renderBody(); } finally { reloading = false; }
|
||||
}, 250);
|
||||
};
|
||||
|
||||
(function init() {
|
||||
if (!$('drawer-actions') || !$('files-tree')) return;
|
||||
req('GET', '/api/local/info').then(function (info) {
|
||||
if (!info || !info.enabled) return;
|
||||
localCapable = true;
|
||||
syncLocalButtons();
|
||||
}).catch(function () { /* 服务器形态:接口 404,保持纯服务器行为 */ });
|
||||
})();
|
||||
})();
|
||||
@@ -49,8 +49,7 @@
|
||||
// 深度思考开关:每次发消息随 body 传给后端,后端会合并该模型的 thinking_params
|
||||
$('deep-think-btn').addEventListener('click', () => {
|
||||
state.deepThink = !state.deepThink;
|
||||
$('deep-think-btn').classList.toggle('on', state.deepThink);
|
||||
toast(state.deepThink ? '深度思考已开启' : '深度思考已关闭');
|
||||
$('deep-think-btn').classList.toggle('on', state.deepThink); // 按钮态即反馈,不再弹 toast
|
||||
});
|
||||
|
||||
// ---------- 任务文件面板(底部浮层:点输入行右侧文件夹按钮展开,遮罩盖住输入区) ----------
|
||||
@@ -330,8 +329,8 @@
|
||||
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 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 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 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="可下载"><use href="#i-file-doc"/></svg>';
|
||||
const name = esc(String(f.filename).split('/').pop() || f.filename);
|
||||
const ftime = fmtTime(f.mtime || f.ctime);
|
||||
const sel = isFileEffectivelySelected(f.filename);
|
||||
@@ -353,10 +352,10 @@
|
||||
(under.length > 0 && under.every(isFileEffectivelySelected));
|
||||
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>' +
|
||||
'<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-count">' + countDirFiles(node) + ' 个文件</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>';
|
||||
}
|
||||
|
||||
@@ -387,7 +386,7 @@
|
||||
sizeEl.textContent = total > 0 ? fmtSize(total) : '';
|
||||
}
|
||||
// 根节点: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
|
||||
? '<span class="crumb" data-path="">' + homeIc + '根目录</span>'
|
||||
: '<span class="crumb cur">' + homeIc + '根目录</span>';
|
||||
@@ -666,8 +665,7 @@
|
||||
ok++;
|
||||
} catch (e) { fail++; toast('删除失败:' + name + ' ' + e.message); }
|
||||
}
|
||||
if (ok) toast('已删除 ' + ok + ' 项');
|
||||
loadFiles(); // 重新拉取并重置选中
|
||||
loadFiles(); // 重新拉取并重置选中;失败已逐条提示,全成功时不弹汇总
|
||||
}
|
||||
$('files-bulk-download').addEventListener('click', bulkDownload);
|
||||
$('files-bulk-delete').addEventListener('click', bulkDelete);
|
||||
@@ -775,8 +773,8 @@
|
||||
function uploadIconSvg(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"><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-image-b"/></svg>'
|
||||
: '<svg class="ic" viewBox="0 0 24 24"><use href="#i-file-doc"/></svg>';
|
||||
}
|
||||
function addUploadCard(file) {
|
||||
const row = $('up-cards');
|
||||
@@ -791,7 +789,7 @@
|
||||
'<div class="up-meta">' + uploadTypeLabel(file.name) + ' · ' + fmtSize(file.size) + '</div>' +
|
||||
'</div>' +
|
||||
'<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>' +
|
||||
'<div class="up-mask"><span class="up-pct">0%</span></div>';
|
||||
const mask = card.querySelector('.up-mask');
|
||||
@@ -910,6 +908,9 @@
|
||||
// 全部成功不再弹提示(卡片已完成态即反馈);有失败才提醒
|
||||
if (errCount) toast('已上传 ' + done + ' 个,失败 ' + errCount + ' 个');
|
||||
loadFiles();
|
||||
// 桌面端左栏文件树是新的浏览入口,上传后要同步(旧面板只在手机端用);
|
||||
// 用 reloadFileTree 保留展开与勾选,refreshFileTree 会把用户展开的目录全收起来
|
||||
if (typeof window.reloadFileTree === 'function') window.reloadFileTree();
|
||||
// 1.2s 后收起进度条(还有别的批次在传就不收)
|
||||
setTimeout(() => {
|
||||
if (uploadBatches.size) return;
|
||||
@@ -1057,7 +1058,7 @@
|
||||
row.innerHTML = state.attachments.map((f, i) =>
|
||||
'<span class="attach-chip"><span class="name">' + esc(f.name) + '</span>' +
|
||||
'<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('');
|
||||
}
|
||||
$('attach-chips').addEventListener('click', e => {
|
||||
@@ -1091,11 +1092,21 @@
|
||||
searchTimer = setTimeout(loadSessionList, 250);
|
||||
});
|
||||
$('drawer-list').addEventListener('click', e => {
|
||||
// 桌面端 hover 删除按钮:先于打开会话处理,点击弹删除确认 modal
|
||||
// 桌面端 hover 行内按钮:先于打开会话处理
|
||||
const popBtn = e.target.closest('.conv-pop');
|
||||
if (popBtn) {
|
||||
e.stopPropagation();
|
||||
// files=1 让新窗口开局直接把侧栏切到文件树(打开后即被 syncUrl 抹掉)
|
||||
window.open('/?s=' + encodeURIComponent(popBtn.dataset.pop) + '&files=1', '_blank', 'noopener');
|
||||
return;
|
||||
}
|
||||
// 删除按钮:点击弹删除确认 modal
|
||||
const delBtn = e.target.closest('.conv-del');
|
||||
if (delBtn) { e.stopPropagation(); deleteSession(delBtn.dataset.del); return; }
|
||||
const item = e.target.closest('.conv-item');
|
||||
if (!item) return;
|
||||
// 设置页现在保留左栏(可在设置中看会话/文件):点会话即退出设置页回到对话。
|
||||
if (typeof closeSettings === 'function' && !$('settings-page').classList.contains('hidden')) closeSettings();
|
||||
openSession(item.dataset.id);
|
||||
if (!drawerMQ.matches) openDrawer(false); // 桌面端侧栏常驻,选完会话不收起来
|
||||
});
|
||||
@@ -1229,9 +1240,40 @@
|
||||
document.addEventListener('touchcancel', e => endDrag(e, false), { passive: true });
|
||||
})();
|
||||
|
||||
// 抽屉底部用户区:整行点击 → 设置主页(逻辑见文末「设置区」一节)
|
||||
$('drawer-user').addEventListener('click', () => {
|
||||
if (!drawerMQ.matches) openDrawer(false); // 桌面端设置页覆盖在会话区上,侧栏保持展开
|
||||
// 抽屉底部图标操作栏:文件树 / 预览 / 设置。
|
||||
// 「文件树」是侧栏两个互斥面板的切换开关:不在文件页 → 切到文件树(高亮),
|
||||
// 再点一次 → 回会话列表(不亮)。预览与设置不占用侧栏,高亮由 preview.js / settings.js 同步。
|
||||
function setDrawerPane(files) {
|
||||
// 窄屏没有文件树(只有输入行右侧的旧文件面板),任何调用方都不允许切过去
|
||||
if (files && !drawerMQ.matches) return;
|
||||
// 还没开始会话 = 没有任务目录:不切过去(否则只能切出一个写着「尚未开始会话」的空面板)
|
||||
if (files && !state.sessionId) return;
|
||||
// 文件树模块没加载成功时不要把一个空面板切出来
|
||||
if (files && typeof window.showFileTree !== 'function') return;
|
||||
const drawer = $('drawer');
|
||||
const changed = drawer.classList.contains('drawer-mode-files') !== files;
|
||||
drawer.classList.toggle('drawer-mode-files', files);
|
||||
$('da-files').classList.toggle('active', files);
|
||||
// 重复点当前项不重干活(不重拉列表/不重渲树),避免白掉请求和滚动位置
|
||||
if (!changed) return;
|
||||
if (files) window.showFileTree();
|
||||
else loadSessionList();
|
||||
// 地址栏跟着侧栏模式走(?s=<id>&files=1):刷新后还停在同一面板
|
||||
if (typeof syncUrl === 'function') syncUrl();
|
||||
}
|
||||
$('da-files').addEventListener('click', () => {
|
||||
setDrawerPane(!$('drawer').classList.contains('drawer-mode-files'));
|
||||
});
|
||||
// 窄屏只保留输入行右侧的旧「任务文件」面板,左栏不再提供文件树(按钮也已 CSS 隐藏)。
|
||||
// 宽屏缩到窄屏时如果正停在文件页,先退回会话列表,避免出现两套文件 UI。
|
||||
drawerMQ.addEventListener('change', (e) => { if (!e.matches) setDrawerPane(false); });
|
||||
// 预览没有独立按钮:桌面端只在文件树里点文件时开窗(关窗走预览栏自己的关闭钮 / Esc)。
|
||||
$('da-settings').addEventListener('click', () => {
|
||||
if (typeof showSettings !== 'function') return;
|
||||
const page = $('settings-page');
|
||||
// 再点一次返回(关设置页);否则打开。不看当前在设置栈的第几层,都当"退出设置"
|
||||
if (page && !page.classList.contains('hidden')) { closeSettings(); return; }
|
||||
if (!drawerMQ.matches) openDrawer(false); // 移动端设置页整屏,抽屉先收起
|
||||
showSettings();
|
||||
});
|
||||
|
||||
|
||||
+266
-50
@@ -1,7 +1,8 @@
|
||||
// 通用文档预览窗(桌面右侧 #pv-pane / 移动端全屏 #fs-viewer)
|
||||
// 通用文档预览窗(桌面分栏 #pv-pane:文件树 | 预览 | 会话 / 移动端全屏 #fs-viewer)
|
||||
// —— 文件列表的点击一律进预览窗:office 走 /preview 预览网关(固定格式前端自拼);
|
||||
// md/txt/代码/json/csv 等文本渲染;html/pdf/图片专用渲染;其余类型显示文件信息占位 + 下载。
|
||||
// 桌面打开时自动折叠左侧历史栏让位,关闭恢复;左右边界可拖拽调宽(记忆在 localStorage)。
|
||||
// 桌面端紧贴左栏文件树右侧:点文件后内容就在旁边,不用横跨整个会话区看。
|
||||
// 右边界可拖拽调宽(记忆在 localStorage)。
|
||||
// 依赖(core.js/chat.js/stream.js/files.js 顶层声明):state $ esc toast mdHtml decorateCodePre
|
||||
// rewriteHtmlDocSrcs rewriteMdImageSrcs openFullscreen setFsSource closeFullscreen
|
||||
// openImageViewer downloadFile openDrawer
|
||||
@@ -14,9 +15,64 @@ const PV_PLAIN = /\.(txt|log)$/i;
|
||||
// 常见代码/配置/数据文本扩展名;无扩展名的文件(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_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 会卡)
|
||||
let pvSeq = 0; // 预览序号:快速连点时旧请求不许再动 DOM
|
||||
// reload: 当前内容的"重新载入"动作(文本类无 iframe,按名重开);为 null 时回退到 reload iframe
|
||||
const pvState = { name: null, url: null, blobUrl: null, reload: null, drawerWasOpen: false, mobilePush: false };
|
||||
const pvState = { name: null, url: null, blobUrl: null, reload: null, mobilePush: false,
|
||||
source: null, srcOn: false, bodyNode: null, srcPre: null };
|
||||
|
||||
function pvDesktop() { return window.matchMedia('(min-width: 960px)').matches; }
|
||||
|
||||
@@ -74,6 +130,54 @@ function pvToolbar(o) {
|
||||
document.getElementById('pv-popup').classList.toggle('hidden', !o.popup);
|
||||
pvState.reload = typeof o.reload === 'function' ? o.reload : null;
|
||||
pvState.url = o.url === undefined ? null : o.url;
|
||||
// 源码钮:o.source 是原文(已渲染过的内容才有),没传就藏起来并回到预览态
|
||||
pvState.source = o.source == null || o.source === '' ? null : String(o.source);
|
||||
pvState.srcOn = false;
|
||||
pvState.srcPre = null;
|
||||
const sb = document.getElementById('pv-src');
|
||||
sb.classList.toggle('hidden', pvState.source == null);
|
||||
sb.classList.remove('active');
|
||||
sb.title = '查看源码';
|
||||
sb.setAttribute('aria-label', '查看源码');
|
||||
}
|
||||
|
||||
// 预览 ↔ 源码互切:不重建预览节点,只把它 display:none 再挂一个等宽 pre,来回切代价很低
|
||||
function pvToggleSrc() {
|
||||
const btn = document.getElementById('pv-src');
|
||||
if (!btn || pvState.source == null || !pvState.bodyNode) return;
|
||||
pvState.srcOn = !pvState.srcOn;
|
||||
if (pvState.srcOn) {
|
||||
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)';
|
||||
const pre = document.createElement('pre');
|
||||
pre.className = 'pv-pre pv-src-pre'; // 源码面板:不加行号的原文(代码预览本身走 .pv-code)
|
||||
pre.textContent = text; // 不用 innerHTML:源码里的标签必须当文本
|
||||
pvState.srcPre = pre;
|
||||
document.getElementById('pv-body').appendChild(pre);
|
||||
pvState.bodyNode.style.display = 'none';
|
||||
} else {
|
||||
if (pvState.srcPre && pvState.srcPre.parentNode) pvState.srcPre.parentNode.removeChild(pvState.srcPre);
|
||||
pvState.srcPre = null;
|
||||
pvState.bodyNode.style.display = '';
|
||||
}
|
||||
btn.classList.toggle('active', pvState.srcOn);
|
||||
const lbl = pvState.srcOn ? '返回预览' : '查看源码';
|
||||
btn.title = 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 (_) {}
|
||||
});
|
||||
}
|
||||
|
||||
// 每次展示内容都过一遍:标题显示相对路径(子目录可见),右上角下载钮随文件走
|
||||
@@ -89,6 +193,11 @@ function pvClearBody() {
|
||||
document.getElementById('pv-body').innerHTML = '';
|
||||
pvState.reload = null; // 换内容/关窗后旧的刷新动作立即失效
|
||||
pvState.url = null; // 新窗口地址同理:不清会残留上一份内容的 blob/网关 URL
|
||||
pvState.source = null; // 源码同样跟内容走,不然会把上一个文件的原文留在按钮里
|
||||
pvState.srcOn = false;
|
||||
pvState.bodyNode = null;
|
||||
pvState.srcPre = null;
|
||||
document.getElementById('pv-src').classList.add('hidden');
|
||||
if (pvState.blobUrl) { try { URL.revokeObjectURL(pvState.blobUrl); } catch (_) {} pvState.blobUrl = null; }
|
||||
}
|
||||
|
||||
@@ -103,8 +212,7 @@ function pvInfoNode(name, sizeText, hint) {
|
||||
const box = document.createElement('div');
|
||||
box.className = 'pv-none';
|
||||
box.innerHTML =
|
||||
'<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>' +
|
||||
'<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>' +
|
||||
'<div class="nm"></div><div class="meta"></div><div class="hint"></div>';
|
||||
box.querySelector('.nm').textContent = String(name || '');
|
||||
box.querySelector('.meta').textContent = sizeText ? sizeText : '';
|
||||
@@ -117,25 +225,27 @@ function pvInfoNode(name, sizeText, hint) {
|
||||
}
|
||||
|
||||
function pvOpenPane() {
|
||||
// 不自动折叠左侧栏:左栏是文件树,打开预览时保持可见(文件树 | 预览 | 会话)。
|
||||
if (!document.body.classList.contains('pv-open')) {
|
||||
pvState.drawerWasOpen = document.getElementById('drawer').classList.contains('open');
|
||||
if (pvState.drawerWasOpen && typeof openDrawer === 'function') openDrawer(false); // 挤压式分栏:折叠左侧让位
|
||||
document.body.classList.add('pv-open');
|
||||
}
|
||||
// 开预览就把侧栏切到文件树:预览就贴在它旁边,切了才能顺手换文件看。
|
||||
// 已经在文件页时 setDrawerPane 内部会因「没变化」而直接返回,不会重复拉树。
|
||||
if (typeof setDrawerPane === 'function') setDrawerPane(true);
|
||||
}
|
||||
|
||||
function pvCloseDoc() {
|
||||
if (!document.body.classList.contains('pv-open')) return;
|
||||
document.body.classList.remove('pv-open', 'pv-max');
|
||||
if (typeof vcsSetMode === 'function') vcsSetMode(false); // 关面板即离开 Git 模式
|
||||
if (typeof pvSetMaxUI === 'function') pvSetMaxUI(false); // 收起时复位放大钮图标(函数声明提升,定义在后亦可)
|
||||
pvClearBody();
|
||||
pvState.name = null; pvState.url = null;
|
||||
if (pvState.drawerWasOpen) {
|
||||
pvState.drawerWasOpen = false;
|
||||
if (typeof openDrawer === 'function') openDrawer(true); // 恢复打开预览前的折叠态
|
||||
}
|
||||
}
|
||||
|
||||
// 侧栏底部没有「预览」按钮:桌面端的预览只有一条入口——在文件树里点文件(点即开窗),
|
||||
// 关窗走预览栏自己的关闭钮 / Esc / 缩到窄屏。所以这里不再维护任何按钮高亮状态。
|
||||
|
||||
// 移动端全屏承载:把节点塞进 #fs-viewer 并展开
|
||||
// opts.bar → 文件预览沉浸模式:顶部独立操作条,内容全宽占满剩余空间
|
||||
// opts.name → 操作条左侧的文件名(仅 bar 模式可见)
|
||||
@@ -201,9 +311,56 @@ async function pvOpenOffice(name, sizeText) {
|
||||
pvState.url = url;
|
||||
}
|
||||
|
||||
// ---------- 站内地址预览:会话流里的链接 / 地址条回车 → 直接挂进预览窗 ----------
|
||||
// 「本机」判定:完全同源,或两端都是本机别名(localhost/127.0.0.1/[::1]/0.0.0.0,端口不究)。
|
||||
// 外链、锚点、mailto、相对路径都不算,调用方自行放行。
|
||||
function pvLocalHost(h) { return h === 'localhost' || h === '127.0.0.1' || h === '::1' || h === '[::1]' || h === '0.0.0.0'; }
|
||||
function pvSameHost(target) {
|
||||
let u;
|
||||
try { u = new URL(target, location.href); } catch (_) { return null; }
|
||||
if (u.origin === location.origin) return u;
|
||||
if (pvLocalHost(u.hostname) && pvLocalHost(location.hostname)) return u;
|
||||
return null;
|
||||
}
|
||||
function pvUrlTitle(url) {
|
||||
try {
|
||||
const u = new URL(url, location.href);
|
||||
return decodeURIComponent(u.pathname.split('/').filter(Boolean).pop() || '') || u.host;
|
||||
} catch (_) { return String(url); }
|
||||
}
|
||||
// iframe 直挂,不走文件读取链路:桌面进右侧分栏,窄屏进全屏浮层。
|
||||
// sandbox 与现有 HTML 预览一致——data-page 页面要靠脚本渲染表格。
|
||||
function pvOpenUrl(url, title) {
|
||||
const desk = pvDesktop();
|
||||
const name = title || pvUrlTitle(url);
|
||||
++pvSeq; // 在途的文件预览请求就此作废,别回来抢 DOM
|
||||
const mkFrame = () => {
|
||||
const fr = document.createElement('iframe');
|
||||
fr.className = desk ? 'pv-frame' : 'fs-html-frame';
|
||||
fr.title = name;
|
||||
fr.setAttribute('sandbox', 'allow-same-origin allow-scripts');
|
||||
fr.src = url;
|
||||
return fr;
|
||||
};
|
||||
if (desk) {
|
||||
pvOpenPane(); pvClearBody();
|
||||
pvHeader(name, '');
|
||||
pvState.name = null; // 不是文件:下载钮收起(按名下载会拼错路径)
|
||||
document.getElementById('pv-download').classList.add('hidden');
|
||||
pvToolbar({ refresh: true, popup: true, reload: () => pvOpenUrl(url, title), url });
|
||||
const t = document.getElementById('pv-title'); // 地址条显示完整地址,可选中复制
|
||||
t.value = url; t.title = url;
|
||||
document.getElementById('pv-body').appendChild(mkFrame());
|
||||
} else {
|
||||
pvOverlayShow(mkFrame(), { bar: true, name });
|
||||
if (!pvState.mobilePush) { try { history.pushState({ pvOffice: 1 }, ''); pvState.mobilePush = true; } catch (_) {} }
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 统一入口:所有文件点击都走这 ----------
|
||||
async function openFilePreview(name, sizeText) {
|
||||
if (!state.sessionId) return;
|
||||
if (typeof vcsSetMode === 'function') vcsSetMode(false); // 点文件即离开 Git 面板(预览/Git 二选一)
|
||||
if (PV_OFFICE.test(name)) { try { await pvOpenOffice(name, sizeText); } catch (e) { toast('预览失败:' + e.message); } return; }
|
||||
let kind = pvKind(name);
|
||||
if (kind === 'pdf' && !navigator.pdfViewerEnabled) kind = 'none'; // WebView 内嵌不了 PDF:给占位卡,不再自动下载
|
||||
@@ -222,9 +379,12 @@ async function openFilePreview(name, sizeText) {
|
||||
}
|
||||
const show = (node, tb) => {
|
||||
if (my !== pvSeq) return;
|
||||
// 节点上挂了 __src(原文)就带进工具条:预览栏据此显示源码钮。手机端的源码钮走 fs-viewer,不掺和。
|
||||
if (node && node.__src != null) { tb = Object.assign({}, tb || tbAll, { source: node.__src }); delete node.__src; }
|
||||
if (desk) {
|
||||
pvClearBody(); pvHeader(name, sizeText);
|
||||
document.getElementById('pv-body').appendChild(node);
|
||||
pvState.bodyNode = node;
|
||||
pvToolbar(tb || tbAll);
|
||||
} else pvOverlayShow(node, { bar: true, name: name });
|
||||
};
|
||||
@@ -287,11 +447,13 @@ async function openFilePreview(name, sizeText) {
|
||||
// 统一等 show() 之后登记,陈旧序号则立即撤销防泄漏。
|
||||
let newBlobUrl = null;
|
||||
if (kind === 'html') {
|
||||
const src = rewriteHtmlDocSrcs(await r.text(), name); // 相对资源改写,否则 about:srcdoc/blob 基准下全 404
|
||||
const raw = await r.text(); // 原文留着做源码面板,改写只用于内嵌显示
|
||||
const src = rewriteHtmlDocSrcs(raw, name); // 相对资源改写,否则 about:srcdoc/blob 基准下全 404
|
||||
const fr = document.createElement('iframe');
|
||||
fr.className = 'pv-frame';
|
||||
fr.setAttribute('sandbox', 'allow-same-origin allow-scripts');
|
||||
fr.srcdoc = src;
|
||||
fr.__src = raw;
|
||||
newBlobUrl = URL.createObjectURL(new Blob([src], { type: 'text/html;charset=utf-8' }));
|
||||
tb = Object.assign({}, tbAll, { url: newBlobUrl }); // 新窗口=改写后的页面(与面板里同一份)
|
||||
node = fr;
|
||||
@@ -302,10 +464,14 @@ async function openFilePreview(name, sizeText) {
|
||||
fr.className = 'pv-frame'; fr.title = String(name); fr.src = u; // 不加 sandbox:内建查看器插件需要 unrestricted 帧
|
||||
node = fr; tb = Object.assign({}, tbAll, { url: u });
|
||||
} else if (kind === 'img') {
|
||||
const u = URL.createObjectURL(await r.blob());
|
||||
// r 只能读一次:svg 先取文本再自己包 blob(也顺便拿到源码面板要的原文)
|
||||
const isSvg = /\.svg$/i.test(name);
|
||||
const svgText = isSvg ? await r.text() : null;
|
||||
const u = URL.createObjectURL(isSvg ? new Blob([svgText], { type: 'image/svg+xml;charset=utf-8' }) : await r.blob());
|
||||
newBlobUrl = u;
|
||||
const im = document.createElement('img');
|
||||
im.className = 'pv-img'; im.src = u; im.alt = String(name);
|
||||
if (isSvg) im.__src = svgText;
|
||||
const g = pvImgGroup(name);
|
||||
im.addEventListener('click', () => openImageViewer(u, String(name).split('/').pop(), g && g.list, g && g.at));
|
||||
node = im; tb = Object.assign({}, tbAll, { url: u });
|
||||
@@ -346,6 +512,49 @@ function pvMdDoc(html, name) {
|
||||
}
|
||||
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;二进制嗅探回退占位卡
|
||||
async function pvTextNode(name, sizeText, r) {
|
||||
const text = await r.text();
|
||||
@@ -360,37 +569,25 @@ async function pvTextNode(name, sizeText, r) {
|
||||
wrap.className = 'msg other';
|
||||
wrap.innerHTML = '<div class="' + cls + ' pv-doc">' + html + '</div>';
|
||||
decorateCodePre(wrap);
|
||||
pvHighlightMdCode(wrap); // 围栏代码块上色(与代码预览同一套配色)
|
||||
const n = wrap.firstChild;
|
||||
// q.fmt=false 表示 marked 不可用、面板就是原文排版:新窗口也按纯文本开,避免空白被折叠
|
||||
n.__tb = q.fmt
|
||||
? { popup: true, url: URL.createObjectURL(new Blob([pvMdDoc(html, name)], { type: 'text/html;charset=utf-8' })) }
|
||||
: { popup: true, url: pvTextUrl(text) };
|
||||
n.__src = text;
|
||||
return n;
|
||||
}
|
||||
if (PV_PLAIN.test(low)) {
|
||||
const wrap = document.createElement('div');
|
||||
wrap.className = 'msg other';
|
||||
wrap.innerHTML = '<div class="bubble-ai pv-doc">' + esc(text) + '</div>';
|
||||
const n = wrap.firstChild; n.__tb = { popup: true, url: pvTextUrl(text) };
|
||||
const n = wrap.firstChild; n.__tb = { popup: true, url: pvTextUrl(text) }; n.__src = text;
|
||||
return n;
|
||||
}
|
||||
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);
|
||||
}
|
||||
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);
|
||||
const holder = pvCodeNode(text, name);
|
||||
holder.__tb = { popup: true, url: pvTextUrl(text) }; // 新窗口用全文,不受面板截断影响
|
||||
holder.__src = text; // 源码面板同样给全文
|
||||
return holder;
|
||||
}
|
||||
|
||||
@@ -432,19 +629,21 @@ async function pvRenderLegacy(name, r, my) {
|
||||
openImageViewer(u, name, g && g.list, g && g.at);
|
||||
} else {
|
||||
const text = await r.text();
|
||||
let cls = 'bubble-ai', html;
|
||||
if (PV_MD.test(name)) {
|
||||
const q = mdHtml(text);
|
||||
html = q.html;
|
||||
if (q.fmt) cls += ' md';
|
||||
html = rewriteMdImageSrcs(html, name);
|
||||
} else {
|
||||
html = esc(text);
|
||||
if (!PV_MD.test(name)) {
|
||||
// 代码/配置/数据:与桌面同一套行号 + Prism 着色(原来在手机上只是纯文本)
|
||||
pvOverlayShow(pvCodeNode(text, name), { bar: true, name: name, source: text });
|
||||
return;
|
||||
}
|
||||
const q = mdHtml(text);
|
||||
let cls = 'bubble-ai';
|
||||
let html = q.html;
|
||||
if (q.fmt) cls += ' md';
|
||||
html = rewriteMdImageSrcs(html, name);
|
||||
const wrap = document.createElement('div');
|
||||
wrap.className = 'msg other';
|
||||
wrap.innerHTML = '<div class="' + cls + '">' + html + '</div>';
|
||||
decorateCodePre(wrap);
|
||||
pvHighlightMdCode(wrap);
|
||||
pvOverlayShow(wrap.firstChild, { bar: true, name: name, source: text }); // 全宽沉浸,eye/复制看原文
|
||||
}
|
||||
}
|
||||
@@ -466,6 +665,7 @@ document.getElementById('pv-max').addEventListener('click', () => {
|
||||
const max = document.body.classList.toggle('pv-max');
|
||||
pvSetMaxUI(max);
|
||||
});
|
||||
document.getElementById('pv-src').addEventListener('click', pvToggleSrc);
|
||||
document.getElementById('pv-refresh').addEventListener('click', () => {
|
||||
if (typeof pvState.reload === 'function') { pvState.reload(); return; }
|
||||
const f = document.getElementById('pv-body').querySelector('iframe');
|
||||
@@ -477,11 +677,16 @@ document.getElementById('pv-popup').addEventListener('click', () => {
|
||||
});
|
||||
// 地址条:点击/聚焦全选——长路径被截断时可选中看全文、直接 Ctrl+C 复制
|
||||
document.getElementById('pv-title').addEventListener('focus', (e) => e.target.select());
|
||||
// 地址条回车跳转:http(s) 网址新标签打开,其余按任务目录相对路径进预览
|
||||
// 地址条回车跳转:本机地址(含 /app/... 这类站内绝对路径)进预览窗,外部网址新开标签,
|
||||
// 其余按任务目录相对路径当文件预览。
|
||||
function pvClean(s) { return String(s || '').trim().replace(/^["']+|["']+$/g, ''); }
|
||||
function pvAddrGo(v) {
|
||||
if (/^https?:\/\//i.test(v)) { window.open(v, '_blank', 'noopener'); return; }
|
||||
if (/^https?:\/\//i.test(v)) {
|
||||
if (pvSameHost(v)) { document.getElementById('pv-title').blur(); pvOpenUrl(v); return; }
|
||||
window.open(v, '_blank', 'noopener'); return;
|
||||
}
|
||||
document.getElementById('pv-title').blur();
|
||||
if (v.charAt(0) === '/' && v.charAt(1) !== '/') { pvOpenUrl(v); return; }
|
||||
openFilePreview(v);
|
||||
}
|
||||
// ---------- 地址条文件名补全:候选取自 files.js 缓存的目录树(filesNodeAt),零请求 ----------
|
||||
@@ -566,23 +771,24 @@ document.getElementById('pv-pane').addEventListener('click', (e) => {
|
||||
const b = e.target.closest('.act-copy');
|
||||
if (b && typeof onCopyClick === 'function') onCopyClick(e);
|
||||
});
|
||||
// 移动端系统返回键:先收起 office 全屏预览
|
||||
// 移动端系统返回键:先收起 iframe 类全屏预览(office 网关 / 站内地址)
|
||||
window.addEventListener('popstate', () => {
|
||||
pvState.mobilePush = false;
|
||||
const fs = document.getElementById('fs-viewer');
|
||||
if (!fs.classList.contains('hidden') && fs.querySelector('.fs-html-frame[src^="/preview/"]')) closeFullscreen();
|
||||
if (!fs.classList.contains('hidden') && fs.querySelector('.fs-html-frame')) closeFullscreen();
|
||||
});
|
||||
// Esc 关闭右栏(未开全屏查看器时)
|
||||
// Esc 关闭预览分栏(未开全屏查看器时)
|
||||
window.addEventListener('keydown', (e) => {
|
||||
if (e.key !== 'Escape') return;
|
||||
if (document.activeElement && document.activeElement.id === 'pv-title') { document.activeElement.blur(); return; } // 地址条聚焦时:先退框不关栏
|
||||
if (!document.getElementById('fs-viewer').classList.contains('hidden')) return;
|
||||
pvCloseDoc();
|
||||
});
|
||||
// 窗口收窄到移动端宽度:右栏收起
|
||||
// 窗口收窄到移动端宽度:预览栏收起
|
||||
window.matchMedia('(min-width: 960px)').addEventListener('change', () => { if (!pvDesktop()) pvCloseDoc(); });
|
||||
|
||||
// ---------- 左缘拖拽调宽(预览/会话列边界):双击复位默认宽度,宽度记在 localStorage ----------
|
||||
// ---------- 右缘拖拽调宽(预览/会话列边界):双击复位默认宽度,宽度记在 localStorage ----------
|
||||
// 预览现在贴在文件树右侧(文件树 | 预览 | 会话),所以手柄在它自己的右缘,往右拖变宽。
|
||||
(function bindPvResize() {
|
||||
const pane = document.getElementById('pv-pane');
|
||||
const saved = Number(localStorage.getItem('pv-w') || 0);
|
||||
@@ -591,21 +797,31 @@ window.matchMedia('(min-width: 960px)').addEventListener('change', () => { if (!
|
||||
const h = document.createElement('div');
|
||||
h.className = 'pv-resizer';
|
||||
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) => {
|
||||
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 (_) {}
|
||||
document.body.classList.add('pv-resizing');
|
||||
});
|
||||
h.addEventListener('pointermove', (e) => {
|
||||
if (!st) return;
|
||||
document.documentElement.style.setProperty('--pv-w', clamp(st.w + (st.x - e.clientX)) + 'px');
|
||||
st.lastX = e.clientX;
|
||||
if (!rafId) rafId = requestAnimationFrame(() => { rafId = 0; commit(); });
|
||||
});
|
||||
function end() {
|
||||
if (!st) return;
|
||||
if (rafId) { cancelAnimationFrame(rafId); rafId = 0; commit(); } // 把最后一帧补上
|
||||
const w = pane.offsetWidth;
|
||||
st = null;
|
||||
document.body.classList.remove('pv-resizing');
|
||||
const w = pane.offsetWidth;
|
||||
if (w) localStorage.setItem('pv-w', String(w));
|
||||
}
|
||||
h.addEventListener('pointerup', end);
|
||||
@@ -619,7 +835,7 @@ window.matchMedia('(min-width: 960px)').addEventListener('change', () => { if (!
|
||||
// —— 通用 UI 卡片(stream.js 转发 SSE ui_card;任何 MCP 服务/工具回包附 type:"ui_card" 块即可产出)——
|
||||
// 产生方契约 {action, arg, title?, note?};新交互在动作注册表加一条即可,未知 action 忽略(向前兼容)。
|
||||
// 图标由前端统一持有(与 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 = {
|
||||
// arg = 相对会话目录的文件路径,点击 = openFilePreview(office 走预览网关,其余类型走文本/图片渲染)
|
||||
open_preview: { go: '预览 ›', hint: '点击打开预览', icon: UI_CARD_ICON_DOC, run: (d) => openFilePreview(d.arg) },
|
||||
|
||||
@@ -31,8 +31,11 @@
|
||||
'<button class="conv-item' + (s.id === state.sessionId ? ' active' : '') + '" data-id="' + esc(s.id) + '">' +
|
||||
'<span class="conv-title">' + esc(s.title || s.id) + '</span>' + drawerStatusDot(s) +
|
||||
'</button>' +
|
||||
'<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"><use href="#i-external"/></svg>' +
|
||||
'</button>' +
|
||||
'<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="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></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>' +
|
||||
'</div>';
|
||||
}
|
||||
@@ -78,6 +81,7 @@
|
||||
state.sessionId = null;
|
||||
state.sessionTitle = '';
|
||||
state.sessionType = 'secretary';
|
||||
if (window.refreshFileTree) window.refreshFileTree();
|
||||
state.pendingModel = '';
|
||||
state.pending = [];
|
||||
renderSendQueue();
|
||||
@@ -89,9 +93,9 @@
|
||||
state.renderedSigs = {};
|
||||
state.streaming = false;
|
||||
if (typeof clearEditState === 'function') clearEditState();
|
||||
syncUrl();
|
||||
setView('welcome'); // 复用 newChat 同样的视图切换路径
|
||||
}
|
||||
toast('已删除会话');
|
||||
loadSessionList();
|
||||
} catch (e) { toast('删除失败:' + e.message); }
|
||||
}
|
||||
@@ -119,6 +123,8 @@
|
||||
}).catch(() => {}).then(() => {
|
||||
sseResyncing = false;
|
||||
if (state.sessionId === id && state.view === 'chat' && !state.es) connectStream();
|
||||
// 断点期间的文件变动看不到任何 SSE,补拉完顺手重刷一次文件树
|
||||
if (typeof window.reloadFileTree === 'function') window.reloadFileTree();
|
||||
});
|
||||
}
|
||||
setInterval(() => {
|
||||
@@ -183,11 +189,32 @@
|
||||
if (Date.now() - state.lastSseAt > 45000) probeSseAlive();
|
||||
});
|
||||
|
||||
// 地址栏跟随当前会话与侧栏模式:?s=<id>[&files=1],刷新/收藏/分享都能回到同一屏
|
||||
function syncUrl() {
|
||||
const id = state.sessionId;
|
||||
let url = '/';
|
||||
if (id) {
|
||||
url = '/?s=' + encodeURIComponent(id);
|
||||
// 侧栏停在文件树时带上 files=1:刷新后还是文件树,不会莫名退回会话列表
|
||||
if ($('drawer').classList.contains('drawer-mode-files')) url += '&files=1';
|
||||
}
|
||||
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) {
|
||||
closeStream();
|
||||
removeTyping();
|
||||
setFilesPanel(false); // 会话切换,收起文件面板防旧列表残留
|
||||
if (typeof pvCloseDoc === 'function') pvCloseDoc(); // 同上:收起文档预览右栏,防旧会话内容残留
|
||||
// 切会话也要收起预览与 Git:里面是上一个会话的文件/仓库,留在旁边容易被当成新会话的
|
||||
closePreviewAll();
|
||||
state.sessionId = id;
|
||||
state.status = '';
|
||||
state.modelId = '';
|
||||
@@ -221,9 +248,20 @@
|
||||
const detail = await req('GET', '/api/sessions/' + id + '?limit=' + CHAT_INIT_PAGE_SIZE);
|
||||
if (state.sessionId !== id) return; // 期间已切到别的会话
|
||||
renderDetail(detail);
|
||||
// 深度思考跟随会话(发消息时落库):只在这里回填,软刷新不动用户未发出的切换
|
||||
state.deepThink = !!(detail.session && detail.session.deep_think);
|
||||
$('deep-think-btn').classList.toggle('on', state.deepThink);
|
||||
connectStream();
|
||||
if (window.refreshFileTree) window.refreshFileTree();
|
||||
syncUrl(); // 详情拿到才写地址栏:坏链接不会把刷新后的页面也钉死在坏会话上
|
||||
} catch (e) {
|
||||
if (state.sessionId === id) toast('打开会话失败:' + e.message);
|
||||
if (state.sessionId === id) {
|
||||
toast('打开会话失败:' + e.message);
|
||||
state.sessionId = null;
|
||||
state.sessionTitle = '';
|
||||
syncUrl();
|
||||
setView('welcome'); // 会话已被删/链接失效:别把「加载中…」留在屏幕上(同时把顶部按钮置灰)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -231,25 +269,72 @@
|
||||
// welcome 经弹窗预选的模型在这里兑现:model_id 建档透传。
|
||||
async function ensureSession() {
|
||||
if (state.sessionId) return state.sessionId;
|
||||
const s = await req('POST', '/api/sessions', { title: '', model_id: state.pendingModel || '', assistant_type: state.mode });
|
||||
const s = await req('POST', '/api/sessions', { title: '', model_id: state.pendingModel || '', assistant_type: state.mode, work_dir: pendingWorkDir || undefined });
|
||||
state.sessionId = s.id;
|
||||
state.sessionTitle = (s && s.title) || '';
|
||||
state.sessionType = (s && s.assistant_type) || state.mode;
|
||||
state.pendingModel = '';
|
||||
if (window.refreshFileTree) window.refreshFileTree();
|
||||
setView('chat');
|
||||
renderHeader();
|
||||
updateHeaderActions();
|
||||
connectStream();
|
||||
syncUrl();
|
||||
return s.id;
|
||||
}
|
||||
|
||||
// ---------- 本地端:新建会话时手选工作目录 ----------
|
||||
// 只在 local/ 启动器(AGENT_LOCAL_PICK=1)下可用:探测 /api/local/info,拿不到就把整条
|
||||
// chip 隐藏,服务器形态完全看不见这个入口。选择只暂存在前端,真正建档时随
|
||||
// POST /api/sessions 提交一次;不选 = work_dir 空串 = 老行为(workspace_root/<会话id>)。
|
||||
let pendingWorkDir = '';
|
||||
|
||||
function renderWelcomeDir() {
|
||||
const pathEl = $('welcome-dir-path');
|
||||
if (!pathEl) return;
|
||||
const chip = $('welcome-dir');
|
||||
pathEl.textContent = pendingWorkDir || '默认(工作区内)';
|
||||
pathEl.title = pendingWorkDir || '默认:每个会话在系统工作目录下单独建档';
|
||||
chip.classList.toggle('is-set', !!pendingWorkDir);
|
||||
$('welcome-dir-clear').classList.toggle('hidden', !pendingWorkDir);
|
||||
}
|
||||
|
||||
async function pickWelcomeDir() {
|
||||
const btn = $('welcome-dir-pick');
|
||||
if (btn.disabled) return;
|
||||
btn.disabled = true;
|
||||
try {
|
||||
// 超时给足 130s:后端对话框上限 120s,这里多留余量,别让前端先断
|
||||
const r = await req('POST', '/api/local/pick-dir', {}, false, 130000);
|
||||
if (r && r.path) { pendingWorkDir = r.path; renderWelcomeDir(); }
|
||||
} catch (e) {
|
||||
toast('选择目录失败:' + e.message);
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
(function initWelcomeDir() {
|
||||
const chip = $('welcome-dir');
|
||||
if (!chip) return;
|
||||
req('GET', '/api/local/info').then(info => {
|
||||
if (!info || !info.enabled) return;
|
||||
chip.classList.remove('hidden');
|
||||
renderWelcomeDir();
|
||||
}).catch(() => { /* 服务器形态:接口 404,整条隐藏 */ });
|
||||
$('welcome-dir-pick').addEventListener('click', pickWelcomeDir);
|
||||
$('welcome-dir-clear').addEventListener('click', () => { pendingWorkDir = ''; renderWelcomeDir(); });
|
||||
})();
|
||||
|
||||
function newChat() {
|
||||
closeStream();
|
||||
removeTyping();
|
||||
setFilesPanel(false); // 新建会话,文件面板随之收起
|
||||
closePreviewAll(); // 预览/Git 都属于上一个会话,新建时一并收起
|
||||
state.sessionId = null;
|
||||
state.sessionTitle = '';
|
||||
state.sessionType = 'secretary';
|
||||
if (window.refreshFileTree) window.refreshFileTree();
|
||||
state.status = '';
|
||||
state.modelId = '';
|
||||
state.schedule = null;
|
||||
@@ -257,6 +342,8 @@
|
||||
renderSendQueue();
|
||||
state.pendingModel = '';
|
||||
state.attachments = [];
|
||||
pendingWorkDir = ''; // 新建会话把上次手选的工作目录也归零(回到默认)
|
||||
renderWelcomeDir();
|
||||
if (typeof clearEditState === 'function') clearEditState();
|
||||
state.streamEl = null;
|
||||
state.streamText = '';
|
||||
@@ -268,6 +355,8 @@
|
||||
userPaused = false;
|
||||
renderAttachChips();
|
||||
clearUploadCards();
|
||||
renderDrawerList(); // sessionId 已置空,重画抽屉把旧会话的选中态清掉
|
||||
syncUrl();
|
||||
setView('welcome');
|
||||
$('chat-view').innerHTML = '';
|
||||
$('msg-input').value = '';
|
||||
@@ -285,7 +374,6 @@
|
||||
const title = String(t).trim();
|
||||
try {
|
||||
await req('PATCH', '/api/sessions/' + state.sessionId, { title: title });
|
||||
toast('已重命名');
|
||||
state.sessionTitle = title;
|
||||
renderHeader();
|
||||
loadSessionList();
|
||||
@@ -403,8 +491,37 @@
|
||||
if (act === 'model') openModelSwitch();
|
||||
else if (act === 'schedule') openScheduleModal();
|
||||
else if (act === 'compact') summarizeChat();
|
||||
else if (act === 'theme') cycleTheme();
|
||||
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,事件只在这里绑一次。
|
||||
(function bindHeaderActions() {
|
||||
document.querySelectorAll('#header-meta [data-act], #header-actions [data-act]').forEach(el => {
|
||||
@@ -417,6 +534,7 @@
|
||||
if (!e.target.closest('#header-actions')) closeHeaderMenu();
|
||||
});
|
||||
document.addEventListener('keydown', e => { if (e.key === 'Escape') closeHeaderMenu(); });
|
||||
syncThemeBtns(); // 按钮图标/文字跟着当前主题落一次
|
||||
})();
|
||||
|
||||
// ---------- 定时任务(弹窗改频次/提示词;无任务时同一弹窗即新建) ----------
|
||||
@@ -736,7 +854,7 @@
|
||||
wrap.innerHTML =
|
||||
'<div class="modal">' +
|
||||
'<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>' +
|
||||
'<h3 id="compress-modal-title">压缩上下文</h3>' +
|
||||
'<div class="modal-body" style="font-size:14px;line-height:1.55;color:#555;padding:4px 0 12px;">' +
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
stack: [],
|
||||
snaps: {}, // 页名 → 静态快照 HTML(setPush 时刷新;右滑返回垫底用)
|
||||
role: 'user', // 当前登录用户角色(admin | user);启动时由 /api/me 回填
|
||||
authEnabled: true, // 是否启用多用户认证(/api/me 404 = 未启用,单用户自用)
|
||||
authEnabled: true, // 是否启用多用户认证(/api/me 返回 auth:false = 未启用,单用户自用)
|
||||
pendingKeys: new Set(), // 已写盘、尚未重启生效的顶层配置段
|
||||
effCfg: null, cfgOrig: '',
|
||||
users: [], userModels: [], // 用户管理页:账号/角色/默认模型 + 可选模型清单
|
||||
@@ -130,23 +130,23 @@
|
||||
function showSettings() {
|
||||
// 普通用户没有设置主页:直接进账户页(栈里只有一页,返回即退出设置)
|
||||
SET.stack = [SET.role === 'admin' ? 'home' : 'account']; SET.snaps = {}; setUnderHide();
|
||||
// 桌面端:打开设置时收起侧边栏让设置页占满窗口,关闭时恢复之前的展开态
|
||||
if (drawerMQ.matches) { drawerWasOpenBeforeSet = document.body.classList.contains('drawer-open'); openDrawer(false); }
|
||||
// 桌面端保留左侧栏:设置页是 #app 内的 absolute 覆盖层,自然只占侧栏右侧区域,
|
||||
// 左栏(会话/文件)保持可见可用。
|
||||
$('settings-page').classList.remove('hidden'); renderSetPage();
|
||||
const b = $('da-settings'); if (b) b.classList.add('active'); // 侧栏底部图标同步选中态
|
||||
}
|
||||
let drawerWasOpenBeforeSet = false;
|
||||
function closeSettings() {
|
||||
SET.stack = []; SET.snaps = {}; setUnderHide();
|
||||
// 退回会话页才重置模型池状态:平台卡全部折叠、余额清空,下次进入重新自动查
|
||||
SET.expandedGroups = {}; SET.balanceByGroup = {}; SET.balanceRequested = {};
|
||||
$('settings-page').classList.add('hidden');
|
||||
if (drawerMQ.matches && drawerWasOpenBeforeSet) { openDrawer(true); drawerWasOpenBeforeSet = false; }
|
||||
const b = $('da-settings'); if (b) b.classList.remove('active');
|
||||
}
|
||||
// 当前页静态快照(顶栏+正文):右滑返回时垫底,呈现原生导航栈的视差感。
|
||||
// 快照里的 id 全部剥除,防止重复 id 干扰 $('…') 查找;仅作动画背景,滑完由 renderSetPage 重渲染真页。
|
||||
function snapSetPage() {
|
||||
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-right">' + $('set-actions').innerHTML + '</div></header>' +
|
||||
'<div class="set-under-body">' + $('set-body').innerHTML + '</div>';
|
||||
@@ -281,17 +281,17 @@
|
||||
// ---------- 页:设置主页(卡片入口) ----------
|
||||
const SET_CARDS = [
|
||||
{ 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,
|
||||
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,
|
||||
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,
|
||||
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,
|
||||
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,
|
||||
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) {
|
||||
setTitle('设置');
|
||||
@@ -303,7 +303,7 @@
|
||||
'<span class="set-ico">' + c.icon + '</span>' +
|
||||
'<span class="set-tt"><span class="set-name">' + c.name + '</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>');
|
||||
}
|
||||
|
||||
@@ -320,23 +320,8 @@
|
||||
for (const ch of String(name || '')) h = (h * 31 + ch.codePointAt(0)) >>> 0;
|
||||
return AVATAR_COLORS[h % AVATAR_COLORS.length];
|
||||
}
|
||||
// 侧边栏底部用户区:展示真实登录用户名,头像样式与设置页 user-card 一致(按用户名取色+首两字)。
|
||||
// 启动校验已经拉到登录用户时直接传入,避免同一次加载重复请求 /api/me;未传入时自拉兜底。
|
||||
async function loadDrawerUser(knownUser) {
|
||||
const av = $('drawer-avatar'), un = $('drawer-user-name');
|
||||
if (!av || !un) return;
|
||||
let name = knownUser ? String(knownUser) : '';
|
||||
if (!name) {
|
||||
try {
|
||||
const r = await req('GET', '/api/me');
|
||||
name = r && r.user ? String(r.user) : '';
|
||||
} catch (_) { return; /* 未启用认证时无 /api/me,保留默认占位 */ }
|
||||
}
|
||||
if (!name) return; // 未登录态(理论上不会出现,401 已自动跳登录页)
|
||||
av.textContent = userInitials(name);
|
||||
av.style.background = avatarColor(name);
|
||||
un.textContent = name;
|
||||
}
|
||||
// 侧栏底部已改成纯图标操作栏,不再展示登录用户名(用户信息仍在设置页「账户」里),
|
||||
// 所以原来的 loadDrawerUser 已随之删除。
|
||||
function userCardHtml(me) {
|
||||
return '<div class="settings-card user-card">' +
|
||||
'<div class="user-avatar" style="background:' + avatarColor(me) + '">' + esc(userInitials(me)) + '</div>' +
|
||||
@@ -351,9 +336,9 @@
|
||||
setActions('');
|
||||
setBody('<div class="set-scroll"><div class="empty-tip">加载中…</div></div>');
|
||||
// 单个 /api/me 判认证开关:启用时中间件保证已登录,user 必有;
|
||||
// 未启用时该路由 404 → 只是没有密码/登出卡,画像仍渲染(未认证 = 空串键隐式单用户)。
|
||||
// 未启用时回 auth:false + user:null → 只是没有密码/登出卡,画像仍渲染(未认证 = 空串键隐式单用户)。
|
||||
let me = null;
|
||||
try { const r = await req('GET', '/api/me'); if (r && r.user) me = r; } catch (_) { /* 404 等一律按无账户信息处理 */ }
|
||||
try { const r = await req('GET', '/api/me'); if (r && r.user) me = r; } catch (_) { /* 一律按无账户信息处理 */ }
|
||||
let p = null, pErr = '';
|
||||
try { p = await req('GET', '/api/profile'); } catch (e) { pErr = String((e && e.message) || e); }
|
||||
if (!ctx()) return;
|
||||
@@ -410,7 +395,7 @@
|
||||
async function setPageUsers(ctx) {
|
||||
setTitle('用户');
|
||||
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>');
|
||||
try {
|
||||
const r = await req('GET', '/api/users');
|
||||
@@ -704,7 +689,7 @@
|
||||
async function setPageService(ctx) {
|
||||
setTitle('服务');
|
||||
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>');
|
||||
try {
|
||||
const [st, cg] = await Promise.all([
|
||||
@@ -784,7 +769,7 @@
|
||||
async function setPageCfgEditor(ctx) {
|
||||
setTitle('config.yml 原文');
|
||||
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>' +
|
||||
'<textarea id="set-editor-area" spellcheck="false" autocomplete="off" autocapitalize="off"></textarea></div>');
|
||||
try {
|
||||
@@ -827,7 +812,7 @@
|
||||
SET.curSkill = null;
|
||||
setTitle('技能管理');
|
||||
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>');
|
||||
try {
|
||||
const rows = await req('GET', '/api/skills');
|
||||
@@ -870,7 +855,7 @@
|
||||
setTitle(SET.curSkill);
|
||||
setActions('<label class="icon-btn" title="上传文件">' +
|
||||
'<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>');
|
||||
try {
|
||||
const d = await req('GET', '/api/skills/' + encodeURIComponent(SET.curSkill));
|
||||
@@ -886,7 +871,7 @@
|
||||
el.innerHTML = '<div class="skill-files">' + d.files.map(f => {
|
||||
const a = encodeURIComponent(f.filename);
|
||||
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-size">' + fmtSize(f.size) + '</span>' +
|
||||
'<button class="file-act" onclick="event.stopPropagation();sUI.editFile(\'' + a + '\')">编辑</button>' +
|
||||
@@ -900,7 +885,7 @@
|
||||
function setPageSkillEditor(ctx) {
|
||||
setTitle(SET.editorLabel || '编辑文件');
|
||||
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>');
|
||||
$('set-editor-area').value = SET.editorText;
|
||||
}
|
||||
@@ -1081,7 +1066,7 @@
|
||||
if (ev) ev.stopPropagation(); // 冒泡到分组头会误触折叠/展开
|
||||
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 行自动查一次余额(每页会话一次;手动刷新不受限)。
|
||||
function toggleModelGroup(gk) {
|
||||
const on = !SET.expandedGroups[gk];
|
||||
@@ -1174,7 +1159,7 @@
|
||||
}).join('') : '';
|
||||
return '<div class="model-group' + (open ? ' open' : '') + '" id="mgrp-' + 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-badge">' + keys.length + ' keys</span>' +
|
||||
'<span class="model-group-meta">' + models.filter(m => m.enable !== false).length + ' / ' + models.length + ' 模型</span>' +
|
||||
@@ -1227,7 +1212,7 @@
|
||||
function setPageModels(ctx) {
|
||||
setTitle('模型池');
|
||||
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>');
|
||||
// 余额与展开态跨设置内导航保持(仅 closeSettings 回会话页时重置),重进本页不重复查余额
|
||||
loadModelCards(ctx);
|
||||
@@ -1275,7 +1260,7 @@
|
||||
}
|
||||
function pfNewModel() {
|
||||
const r = { ref: null, id: '', vision: true, enable: true, display_name: '', profile: '',
|
||||
extra_params: '', thinking_params: '', reasoning_ack_field: '', adv: false };
|
||||
extra_params: '', thinking_params: '', reasoning_ack_field: '', max_context: 0, adv: false };
|
||||
if (pfEdit) applyModelDefaults(r, pfEdit.preset);
|
||||
return r;
|
||||
}
|
||||
@@ -1298,6 +1283,7 @@
|
||||
extra_params: pfJsonText(m.extra_params),
|
||||
thinking_params: pfJsonText(m.thinking_params),
|
||||
reasoning_ack_field: m.reasoning_ack_field || '',
|
||||
max_context: Number(m.max_context) || 0,
|
||||
adv: false,
|
||||
})),
|
||||
};
|
||||
@@ -1378,6 +1364,7 @@
|
||||
'<label class="mpe-line"><span>请求参数</span><textarea rows="2" spellcheck="false" placeholder=\'{"key":"value"}\' oninput="sUI.mModField(' + i + ',\'extra_params\',this.value)">' + esc(r.extra_params) + '</textarea></label>' +
|
||||
'<label class="mpe-line"><span>思考参数</span><textarea rows="2" spellcheck="false" placeholder=\'{"reasoning_effort":"max"}\' oninput="sUI.mModField(' + i + ',\'thinking_params\',this.value)">' + esc(r.thinking_params) + '</textarea></label>' +
|
||||
'<label class="mpe-line"><span>思考链回传</span><input type="text" placeholder="回传字段名" value="' + att(r.reasoning_ack_field) + '" oninput="sUI.mModField(' + i + ',\'reasoning_ack_field\',this.value)"></label>' +
|
||||
'<label class="mpe-line"><span>压缩阈值</span><input type="number" min="0" step="1000" placeholder="0=不自动压缩" value="' + att(r.max_context || 0) + '" oninput="sUI.mModField(' + i + ',\'max_context\',this.value)"></label>' +
|
||||
'</div>' : '';
|
||||
return '<div class="mpe-mcard">' +
|
||||
'<div class="mpe-row">' +
|
||||
@@ -1441,6 +1428,8 @@
|
||||
if (Object.keys(tp).length) nv.thinking_params = tp;
|
||||
const ra = String(r.reasoning_ack_field || '').trim();
|
||||
if (ra) nv.reasoning_ack_field = ra;
|
||||
const mc = Math.max(0, parseInt(r.max_context, 10) || 0);
|
||||
if (mc) nv.max_context = mc;
|
||||
return nv;
|
||||
}
|
||||
// 根据工作态算批量编辑:原地改(值变更项) → 删行(降序) → 新增行(append)。
|
||||
@@ -1517,6 +1506,12 @@
|
||||
} else if (ra !== curRa) {
|
||||
edits.push({ path: mp.concat('reasoning_ack_field'), value: ra });
|
||||
}
|
||||
// 压缩阈值:0 = 删键(缺省不写),避免无意义重写文件
|
||||
const curMc = Number(om.max_context) || 0;
|
||||
const mc = Math.max(0, parseInt(r.max_context, 10) || 0);
|
||||
if (mc !== curMc) {
|
||||
edits.push(mc ? { path: mp.concat('max_context'), value: mc } : { path: mp.concat('max_context'), op: 'delete' });
|
||||
}
|
||||
} else {
|
||||
edits.push({ op: 'append', path: ['platforms', pfEdit.idx, 'models'], value: pfModelValue(r) });
|
||||
}
|
||||
@@ -1627,7 +1622,7 @@
|
||||
async function setPageMcp(ctx) {
|
||||
setTitle('MCP 服务');
|
||||
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>');
|
||||
await loadMcpList(ctx);
|
||||
}
|
||||
@@ -1700,13 +1695,16 @@
|
||||
const txt = f.secret ? (v ? '已配置' : '--') : (v ? String(v) : '--');
|
||||
return '<div class="cfg-kv"><label>' + esc(f.label || f.header) + '</label><b>' + esc(txt) + '</b></div>';
|
||||
}).join('');
|
||||
// 地址一律显示真实配置:预设地址只是容器形态的缺省值,本地形态是 127.0.0.1:809x,
|
||||
// 照抄预设会与「已连接」徽章自相矛盾。
|
||||
const urlTxt = (s ? (s.url || '') : p.url) || '';
|
||||
return '<div class="model-card' + (mode === 'disable' ? ' off' : '') + '"' +
|
||||
' onclick="mcpUI.' + (s ? 'editPreset' : 'addPreset') + '(\'' + att(p.key) + '\')">' +
|
||||
'<div class="model-card-head">' +
|
||||
'<span class="model-card-name">' + esc(p.label || p.key) + '</span>' +
|
||||
state +
|
||||
'</div>' +
|
||||
'<div class="cfg-kv"><label>地址</label><b>' + esc(p.url) + '</b></div>' + kv +
|
||||
'<div class="cfg-kv"><label>地址</label><b>' + esc(urlTxt) + '</b></div>' + kv +
|
||||
'</div>';
|
||||
}
|
||||
// MCP 卡:头部 = 名称 + url + mode 状态;体内 = headers 键值列表。整卡点击进入编辑。
|
||||
@@ -1735,7 +1733,8 @@
|
||||
'</div>';
|
||||
}
|
||||
// 弹窗打开:add 模式 (idx=null) → 空工作态;edit 模式 → 从当前配置复制。
|
||||
// presetKey 有值 = 内置服务模式:url/name/mode 是契约(只读),表单由预设的 fields 生成。
|
||||
// presetKey 有值 = 内置服务模式:name/mode 是契约(只读),url 可改(地址随部署形态变,预设只给缺省值),
|
||||
// 表单由预设的 fields 生成。
|
||||
function openMcpEditor(idx, presetKey) {
|
||||
const preset = presetKey ? (presetMcpList().find(p => p.key === presetKey) || null) : null;
|
||||
const add = idx == null;
|
||||
@@ -1768,9 +1767,11 @@
|
||||
}
|
||||
$('mce-title').textContent = (add ? '添加 ' : '编辑 ') + (preset ? preset.label : 'MCP 服务');
|
||||
$('mce-name').value = preset ? preset.key : (add ? '' : (s.name || ''));
|
||||
$('mce-url').value = preset ? preset.url : (add ? '' : (s.url || ''));
|
||||
// 预填优先级:当前配置 > 预设缺省值。url 不锁只读——容器形态是 mcp_*:3000,本地形态是
|
||||
// 127.0.0.1:809x,漏改这里用户就看不到也改不了真实地址。
|
||||
$('mce-url').value = add ? (preset ? preset.url : '') : (s.url || (preset ? preset.url : ''));
|
||||
$('mce-name').readOnly = !!preset;
|
||||
$('mce-url').readOnly = !!preset;
|
||||
$('mce-url').readOnly = false;
|
||||
// 运行配置里的 timeout_ms 已被 config.js 填上缺省值,所以这里显示的就是当前生效值(没配则为 60000)。
|
||||
$('mce-timeout').value = add || s.timeout_ms == null ? '' : String(s.timeout_ms);
|
||||
// 预设的 mode 是契约(asr / image_task 必须 skill 才不会把一堆转写/生成工具塞进每轮工具表),
|
||||
@@ -1903,11 +1904,13 @@
|
||||
if (!Number.isFinite(tmo) || tmo < 1000 || tmo > 600000) throw new Error('超时要填 1000 ~ 600000 毫秒(留空 = 默认 60s)');
|
||||
tmo = Math.round(tmo);
|
||||
}
|
||||
// 内置服务的 name/url 是契约(表单只读),只有自定义服务才从输入框取
|
||||
const name = preset ? preset.key : $('mce-name').value.trim();
|
||||
const url = preset ? preset.url : $('mce-url').value.trim();
|
||||
const headers = preset ? presetHeaders() : plainHeaders();
|
||||
// name 是契约(预设的服务名固定);url 不再是契约——展示与写盘均以 config 为准,
|
||||
// 输入框里默认的就是预设值,改了就存。
|
||||
const add = mcpEdit.idx < 0;
|
||||
const cur = add ? {} : (SET.cfgMcp[mcpEdit.idx] || {});
|
||||
const name = preset ? preset.key : $('mce-name').value.trim();
|
||||
const url = $('mce-url').value.trim();
|
||||
const headers = preset ? presetHeaders() : plainHeaders();
|
||||
if (add) {
|
||||
if (!url) throw new Error('请填写 url');
|
||||
const obj = { url };
|
||||
@@ -1917,12 +1920,10 @@
|
||||
if (Object.keys(headers).length) obj.headers = headers;
|
||||
edits.push({ op: 'append', path: ['mcp_servers'], value: obj });
|
||||
} else {
|
||||
const cur = SET.cfgMcp[mcpEdit.idx] || {};
|
||||
if (!preset) {
|
||||
if (!url) throw new Error('请填写 url');
|
||||
if (name !== (cur.name || '')) edits.push({ path: ['mcp_servers', mcpEdit.idx, 'name'], value: name });
|
||||
if (url !== (cur.url || '')) edits.push({ path: ['mcp_servers', mcpEdit.idx, 'url'], value: url });
|
||||
}
|
||||
// 自定义服务:name/url 都能改;内置服务只允许改 url(name/mode 是契约)
|
||||
if (!url) throw new Error('请填写 url');
|
||||
if (!preset && name !== (cur.name || '')) edits.push({ path: ['mcp_servers', mcpEdit.idx, 'name'], value: name });
|
||||
if (url !== (cur.url || '')) edits.push({ path: ['mcp_servers', mcpEdit.idx, 'url'], value: url });
|
||||
// mode:默认值不写进文件(选 advertise 就删键)
|
||||
if ((cur.mode || 'advertise') !== mode) edits.push(mode === 'advertise'
|
||||
? { path: ['mcp_servers', mcpEdit.idx, 'mode'], op: 'delete' }
|
||||
@@ -2057,35 +2058,42 @@
|
||||
drawerMQ.addEventListener('change', e => openDrawer(e.matches));
|
||||
// 页面加载时校验 cookie 身份:防止 localStorage 旧 token 通过 autoRestore 恢复错误用户
|
||||
(async () => {
|
||||
let verifiedUser = null; // 校验结果顺带复用给侧边栏,避免同一次加载请求两次 /api/me
|
||||
try {
|
||||
const res = await fetch('/api/me', { credentials: 'include' });
|
||||
if (res.ok) {
|
||||
const j = await res.json();
|
||||
if (!j.user) {
|
||||
if (j.auth === false) {
|
||||
// 未启用多用户认证(单用户自用,本地模式即此形态):没有登录态可校验,全部设置可见
|
||||
SET.role = 'admin';
|
||||
SET.authEnabled = false;
|
||||
} else if (!j.user) {
|
||||
// cookie 无效或用户已从配置中移除 → 彻底清理所有前端凭据并跳登录
|
||||
localStorage.removeItem('agent_token');
|
||||
sessionStorage.removeItem('agent_creds'); // 旧版本遗留的 Basic 凭据,顺带清理
|
||||
location.href = '/logout';
|
||||
return;
|
||||
} else {
|
||||
SET.role = j.role === 'admin' ? 'admin' : 'user';
|
||||
SET.authEnabled = true;
|
||||
}
|
||||
verifiedUser = String(j.user);
|
||||
SET.role = j.role === 'admin' ? 'admin' : 'user';
|
||||
SET.authEnabled = true;
|
||||
} else {
|
||||
// /api/me 404 = 未启用多用户认证:单用户自用,全部设置可见(用户管理页因 auth 关闭而隐藏)
|
||||
// 兜底:改契约之前的旧后端在未启用认证时该路由不存在(404),按未启用处理
|
||||
SET.role = 'admin';
|
||||
SET.authEnabled = false;
|
||||
}
|
||||
} catch (_) { /* 网络错误放过,让后续请求正常走 */ }
|
||||
loadSessionList();
|
||||
loadDrawerUser(verifiedUser); // 侧边栏底部展示真实登录用户(未启用鉴权/拉取失败时静默回退默认占位)
|
||||
// 侧栏底部已是纯图标操作栏(不展示用户信息),不再需要 loadDrawerUser
|
||||
// 会话深链 /?s=<session_id>:数据页面(/app/{task_id}/...)的「返回会话」FAB 用——
|
||||
// task_id 即会话 id(engine 里 1:1),启动时消费一次即 replaceState 抹掉参数,
|
||||
// 避免刷新/分享时被钉回该会话;会话已删则 openSession 自行报错,落在 welcome。
|
||||
const deep = new URLSearchParams(location.search).get('s');
|
||||
// task_id 即会话 id(engine 里 1:1)。地址栏常驻 ?s= 不抹掉,刷新/收藏/分享都能回到同一会话;
|
||||
// 会话已删时 openSession 会自己回落到 welcome 并把 URL 清回 /。
|
||||
const params = new URLSearchParams(location.search);
|
||||
const deep = params.get('s');
|
||||
if (deep) {
|
||||
history.replaceState(null, '', '/');
|
||||
openSession(deep);
|
||||
openSession(deep).then(() => {
|
||||
// 从侧栏「在新窗口打开」进来(带 files=1):开局直接把侧栏切到文件树;
|
||||
// 窄屏/无会话/文件树未加载时 setDrawerPane 内部会自行忽略
|
||||
if (params.get('files') === '1' && typeof setDrawerPane === 'function') setDrawerPane(true);
|
||||
});
|
||||
}
|
||||
})();
|
||||
|
||||
@@ -98,13 +98,19 @@
|
||||
// ---------- 待发送条幅 ----------
|
||||
// 队列本身在服务端(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"><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"><use href="#i-trash"/></svg>';
|
||||
|
||||
function renderSendQueue() {
|
||||
const box = $('send-queue');
|
||||
if (!box) return;
|
||||
const list = state.pending || [];
|
||||
// 条幅增减会改 chat-view 的 clientHeight,浏览器不会替你补滚动:
|
||||
// 改动前先记住是不是贴底,贴底就强制滚回去,否则最后一条消息被裁在视口外。
|
||||
const keepBottom = typeof isNearBottom === 'function' ? isNearBottom() : false;
|
||||
box.classList.toggle('hidden', !list.length);
|
||||
if (!list.length) { box.innerHTML = ''; return; }
|
||||
box.innerHTML = list.map((it, i) => {
|
||||
box.innerHTML = list.length ? list.map((it, i) => {
|
||||
const busy = it.mode === 'interject' || it.mode === 'now';
|
||||
const tag = it.mode === 'now' ? '<span class="sq-tag">正在中断…</span>'
|
||||
: it.mode === 'interject' ? '<span class="sq-tag">等待当前步骤…</span>'
|
||||
@@ -116,11 +122,14 @@
|
||||
return '<div class="sq-item' + (busy ? ' sq-busy' : '') + '" data-qid="' + esc(it.id) + '">' +
|
||||
'<span class="sq-text" title="' + esc(it.content) + '">' + esc(it.content) + '</span>' +
|
||||
tag + acts +
|
||||
'<button class="sq-x" data-act="cancel" title="取消这条">×</button></div>';
|
||||
}).join('');
|
||||
'<button class="sq-act" data-act="recall" title="撤回到输入框,重新编辑" aria-label="撤回编辑">' + SQ_EDIT_ICON + '</button>' +
|
||||
'<button class="sq-act" data-act="cancel" title="删除这条" aria-label="删除这条">' + SQ_TRASH_ICON + '</button></div>';
|
||||
}).join('') : '';
|
||||
// 双帧补滚:hidden 类与 textarea 高度都是本帧生效,rAF 后再跟一次才稳
|
||||
if (keepBottom && typeof scrollBottom === 'function') { scrollBottom(); requestAnimationFrame(scrollBottom); }
|
||||
}
|
||||
|
||||
// 条幅按钮:× 取消;干预/立即发送升级队首(服务端只在安全边界真正投递)。
|
||||
// 条幅按钮:笔=撤回编辑(正文退回输入框),垃圾桶=直接丢弃;干预/立即发送升级队首。
|
||||
async function onSendQueueClick(e) {
|
||||
const btn = e.target.closest('#send-queue button[data-act]');
|
||||
if (!btn || !state.sessionId) return;
|
||||
@@ -128,20 +137,34 @@
|
||||
const qid = item && item.dataset.qid;
|
||||
if (!qid) return;
|
||||
const act = btn.dataset.act;
|
||||
const isDel = act === 'recall' || act === 'cancel'; // 两者都是删队列项,区别只在要不要回填
|
||||
// 撤回文本必须在请求前取:DELETE 的响应里这条已经没了
|
||||
const draft = act === 'recall' ? ((state.pending || []).find(x => x.id === qid) || {}).content || '' : '';
|
||||
btn.disabled = true;
|
||||
try {
|
||||
const base = '/api/sessions/' + state.sessionId + '/pending/' + encodeURIComponent(qid);
|
||||
const r = act === 'cancel' ? await req('DELETE', base) : await req('POST', base, { action: act });
|
||||
const r = isDel ? await req('DELETE', base) : await req('POST', base, { action: act });
|
||||
if (r && Array.isArray(r.pending)) { state.pending = r.pending; renderSendQueue(); }
|
||||
if (act === 'cancel') return;
|
||||
if (r && r.delivered) return; // 回合已结束:服务端直接投递,等 user_message 画气泡
|
||||
toast(act === 'now' ? '已请求中断,随后立即发送' : '已请求干预:当前步骤结束后插话');
|
||||
if (isDel) { if (draft) recallToInput(draft); return; }
|
||||
// 干预/立即发送:条幅自己会变成「等待当前步骤…」/「正在中断…」,不再弹 toast
|
||||
} catch (err) {
|
||||
toast('操作失败:' + err.message);
|
||||
renderSendQueue();
|
||||
}
|
||||
}
|
||||
|
||||
// 撤回:塞回输入框(撤回段在前、已有草稿在后,与发送失败的兜底同序),光标停在撤回段末尾
|
||||
function recallToInput(text) {
|
||||
const ta = $('msg-input');
|
||||
if (!ta) return;
|
||||
ta.value = text + (ta.value ? '\n' + ta.value : '');
|
||||
autosize();
|
||||
updateSendBtn();
|
||||
ta.focus({ preventScroll: true }); // 别让浏览器为露出输入框去滚页面,聊天区的位置由下面统一管
|
||||
try { ta.setSelectionRange(text.length, text.length); } catch (_) {}
|
||||
if (typeof scrollBottom === 'function') { scrollBottom(); requestAnimationFrame(scrollBottom); }
|
||||
}
|
||||
|
||||
const sendQueueBox = $('send-queue');
|
||||
if (sendQueueBox) sendQueueBox.addEventListener('click', onSendQueueClick);
|
||||
|
||||
@@ -290,6 +313,7 @@
|
||||
state.streamEl.className = 'bubble-ai' + (r.fmt ? ' md' : ''); // 增量期间是纯文本,收尾统一换 md 排版
|
||||
state.streamEl.innerHTML = r.html;
|
||||
decorateCodePre(state.streamEl); // 流式期间不插按钮(每帧整块换 innerHTML),收尾统一装饰一次
|
||||
pvHighlightMdCode(state.streamEl); // 围栏代码块上色
|
||||
} else {
|
||||
// 无文本时去掉气泡(纯工具调用/纯思考也要保留思考面板)
|
||||
state.streamEl.remove();
|
||||
@@ -303,18 +327,18 @@
|
||||
bubble.className = 'bubble-ai' + (r.fmt ? ' md' : '');
|
||||
bubble.innerHTML = r.html;
|
||||
decorateCodePre(bubble);
|
||||
pvHighlightMdCode(bubble);
|
||||
state.streamWrap.appendChild(bubble);
|
||||
}
|
||||
// 「压缩」总结回合的最终答复(后端已保证只有压缩回合里首条无工具调用的收尾回复才带 is_summary,
|
||||
// 中间 AI 回复已按普通消息渲染):把已流式输出的气泡装进摘要卡片(与历史重渲染同款样式),
|
||||
// 并标记 wrap 为 msg-summary-live:archiveDomBeforeSummary 据此定位摘要卡片,之前的旧消息收进存档容器。
|
||||
// open=true 让用户立刻读到;后续轮次不自动折起(卡片可手动点 summary 收起)。
|
||||
// 摘要卡片默认收起(与画像快照/渠道/记忆同一种交互),用户想读时点开。
|
||||
// 防重:同一 streamWrap 已有卡片则不再重复插入(保护 SSE 重连重发等场景)。
|
||||
if (d.is_summary && hasText && state.streamWrap && !state.streamWrap.querySelector('.msg-summary')) {
|
||||
const wrap0 = state.streamWrap;
|
||||
const det = document.createElement('details');
|
||||
det.className = 'msg-summary';
|
||||
det.open = true;
|
||||
det.innerHTML = summaryHeaderHtml() + '<div class="msg-summary-body"></div>';
|
||||
const body = det.querySelector('.msg-summary-body');
|
||||
const bubble = wrap0.querySelector('.bubble-ai');
|
||||
@@ -473,6 +497,9 @@
|
||||
state.toolCallStreaming = {}; // 流式参数早卡映射随会话/回合重置
|
||||
updateScrollBottomBtn();
|
||||
loadSessionList();
|
||||
// 一轮完整跑完(agent 循环退出才发 done):工具/技能产物可能新增或改名,文件树就地刷新;
|
||||
// 不在文件树面板时 reloadFileTree 只标脏,等切回去再重拉
|
||||
if (typeof window.reloadFileTree === 'function') window.reloadFileTree();
|
||||
});
|
||||
// 服务端首次交互后自动生成的标题(finalize 后约 1s 到达):即时刷新顶栏 + 重拉会话列表(PC 常驻侧边栏/移动抽屉)
|
||||
es.addEventListener('title', ev => {
|
||||
@@ -517,7 +544,7 @@
|
||||
try { text = decodeURIComponent(escape(atob(copyBtn.dataset.b64 || ''))); } catch (_) {}
|
||||
}
|
||||
const ok = await copyText(text);
|
||||
toast(ok ? '已复制' : '复制失败');
|
||||
if (!ok) toast('复制失败');
|
||||
if (ok) {
|
||||
copyBtn.classList.add('copied');
|
||||
setTimeout(() => copyBtn.classList.remove('copied'), 1200);
|
||||
@@ -538,7 +565,6 @@
|
||||
btn.disabled = true;
|
||||
try {
|
||||
await req('DELETE', '/api/sessions/' + state.sessionId + '/messages/' + msgId);
|
||||
toast('已删除');
|
||||
// 按已加载量分页重拉(长会话删一条不该退回全量重建)
|
||||
const detail = await req('GET', '/api/sessions/' + state.sessionId + '?limit=' + Math.max(CHAT_PAGE_SIZE, state.chatLoadedCount));
|
||||
if (state.view === 'chat') renderDetail(detail);
|
||||
@@ -702,6 +728,21 @@
|
||||
$('chat-view').addEventListener('click', imgViewerDelegate);
|
||||
$('fs-viewer').addEventListener('click', imgViewerDelegate);
|
||||
|
||||
// ---------- 会话流里的本机链接:进预览窗 ----------
|
||||
// 只拦本机 host(同源 / localhost 别名);外链、锚点、mailto、相对路径维持浏览器默认。
|
||||
// 修饰键与中键放行,留着「我就是要新开一个标签页」这个出口。
|
||||
function linkPreviewDelegate(e) {
|
||||
if (e.button !== 0 || e.ctrlKey || e.metaKey || e.shiftKey || e.altKey) return;
|
||||
const a = e.target.closest('a[href]');
|
||||
if (!a) return;
|
||||
const href = a.getAttribute('href') || '';
|
||||
if (!/^(https?:\/\/|\/(?!\/))/i.test(href) || !pvSameHost(href)) return;
|
||||
e.preventDefault();
|
||||
const txt = (a.textContent || '').trim();
|
||||
pvOpenUrl(href, txt && txt.length <= 40 ? txt : null);
|
||||
}
|
||||
$('chat-view').addEventListener('click', linkPreviewDelegate);
|
||||
|
||||
// 图片全屏查看器:transform 缩放+平移。双指捻合缩放(1~6x)、放大后单指/鼠标拖动、双击切 2.5x。
|
||||
// 第 3 参 list([{src,alt}] 或 [src]) 传入「同组图片」时开启左右滑动切换;第 4 参 at 指定起始下标。
|
||||
// 切图用双层 img 做真正的分页位移(旧图跟手滑出、新图同步滑入),并在开图时预取相邻图,
|
||||
|
||||
@@ -0,0 +1,275 @@
|
||||
// Git 面板(复用 #pv-pane:预览 / Git 二选一,由 body.pv-mode-vcs 切换)。
|
||||
// 三个视图:list(提交历史 + 未提交入口)/ detail(提交详情)/ worktree(未提交改动)。
|
||||
// 后两者共用一个渲染器,区别只在头部有没有 commit 信息。
|
||||
// 不做自动刷新:打开、切视图、点刷新时才请求。
|
||||
// 依赖(全局):state esc toast req pvOpenPane pvHeader pvToolbar pvClearBody pvState pvDesktop openFilePreview
|
||||
'use strict';
|
||||
(function () {
|
||||
const PAGE = 30;
|
||||
// view: list | detail | worktree;cur: 当前详情响应;lastPreview: 进 Git 前预览的文件(切回用)
|
||||
const st = { view: 'list', sid: '', repo: null, commits: [], next: null, cur: null, lastPreview: null, seq: 0 };
|
||||
|
||||
function bodyEl() { return document.getElementById('pv-body'); }
|
||||
function sid() { return (state && state.sessionId) || ''; }
|
||||
|
||||
function api(p) {
|
||||
return req('GET', '/api/sessions/' + encodeURIComponent(sid()) + p);
|
||||
}
|
||||
|
||||
// 仓库路径显示在地址条上(地址条是现成的路径位,不另开头部)
|
||||
function setAddr(repo) {
|
||||
const t = document.getElementById('pv-title');
|
||||
if (!t || !repo) return;
|
||||
t.value = repo.root || '';
|
||||
t.title = (repo.root || '') + (repo.branch ? ' · ' + repo.branch : '');
|
||||
}
|
||||
|
||||
function fmtTime(iso) {
|
||||
const d = new Date(iso);
|
||||
if (isNaN(d.getTime())) return String(iso || '');
|
||||
const p = (n) => (n < 10 ? '0' + n : '' + n);
|
||||
return d.getFullYear() + '-' + p(d.getMonth() + 1) + '-' + p(d.getDate()) + ' ' + p(d.getHours()) + ':' + p(d.getMinutes());
|
||||
}
|
||||
|
||||
const BADGE = { A: '新增', D: '删除', R: '改名', M: '修改', U: '未跟踪' };
|
||||
|
||||
function errBox(text, retry) {
|
||||
bodyEl().innerHTML =
|
||||
'<div class="pv-err"><div class="vcs-err-t"></div>' + (retry ? '<button type="button" class="vcs-retry">重试</button>' : '') + '</div>';
|
||||
bodyEl().querySelector('.vcs-err-t').textContent = text;
|
||||
const b = bodyEl().querySelector('.vcs-retry');
|
||||
if (b) b.addEventListener('click', retry);
|
||||
}
|
||||
|
||||
function reasonText(reason) {
|
||||
if (reason === 'no_git') return '这个环境没有 git 命令。';
|
||||
if (reason === 'bad_rev') return '提交不存在,可能已被改写或清理。';
|
||||
if (reason === 'timeout') return 'git 执行超时,仓库可能过大。';
|
||||
if (reason === 'not_repo') return '未找到 git 仓库:当前会话目录及其上级都不是仓库。';
|
||||
return '读取失败:' + (reason || '未知错误');
|
||||
}
|
||||
|
||||
// ---------- 列表 ----------
|
||||
function renderList() {
|
||||
const parts = [];
|
||||
parts.push('<div class="vcs-list">');
|
||||
if (st.repo) {
|
||||
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) {
|
||||
parts.push('<div class="vcs-item wt" data-act="worktree">' +
|
||||
'<div class="t">未提交的改动</div>' +
|
||||
'<div class="m">' + st.worktree.files + ' 个文件有变动</div></div>');
|
||||
}
|
||||
const up = st.repo && st.repo.upstream;
|
||||
for (const c of st.commits) {
|
||||
const atUp = up && c.id === up.id;
|
||||
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>');
|
||||
}
|
||||
if (!st.commits.length && !(st.worktree && st.worktree.files)) {
|
||||
parts.push('<div class="vcs-empty">还没有提交记录</div>');
|
||||
}
|
||||
if (st.next) parts.push('<button type="button" class="vcs-more" data-act="more">加载更多</button>');
|
||||
parts.push('</div>');
|
||||
bodyEl().innerHTML = parts.join('');
|
||||
}
|
||||
|
||||
// ---------- 详情(提交 / 未提交共用)----------
|
||||
// 语法高亮:与预览共用 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) +
|
||||
'</span><span class="n">' + (newNo == null ? '' : newNo) + '</span><span class="c">' + codeEsc(text, lang) + '</span></div>';
|
||||
}
|
||||
|
||||
// 行号自己推:@@ -a,b +c,d @@ 之后的上下文/+/- 分别推进两个计数器
|
||||
function patchHtml(f) {
|
||||
if (f.binary) return '<div class="vcs-nodiff">二进制文件,不显示差异</div>';
|
||||
if (!f.patch) return '<div class="vcs-nodiff">没有可显示的差异</div>';
|
||||
const out = [];
|
||||
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;
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i];
|
||||
if (i === lines.length - 1 && line === '') break; // 末尾换行不算内容行
|
||||
if (line.slice(0, 2) === '@@') {
|
||||
const m = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(line);
|
||||
if (m) { oldNo = Number(m[1]); newNo = Number(m[2]); inHunk = true; }
|
||||
out.push('<div class="vcs-line h"><span class="n"></span><span class="n"></span><span class="c">' + esc(line) + '</span></div>');
|
||||
continue;
|
||||
}
|
||||
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; }
|
||||
const c = line.charAt(0);
|
||||
if (c === '+') out.push(lineHtml('a', null, newNo++, line.slice(1), lang));
|
||||
else if (c === '-') out.push(lineHtml('d', oldNo++, null, line.slice(1), lang));
|
||||
else out.push(lineHtml('', oldNo++, newNo++, line.slice(1), lang));
|
||||
if (++rows > 3000) { out.push('<div class="vcs-nodiff">行数过多,剩余部分已隐藏</div>'); break; }
|
||||
}
|
||||
return out.join('') || '<div class="vcs-nodiff">仅改名或模式变更,没有内容差异</div>';
|
||||
}
|
||||
|
||||
function fileHtml(f, idx, openAll) {
|
||||
const open = openAll ? ' open' : '';
|
||||
return '<div class="vcs-file' + open + '" data-i="' + idx + '">' +
|
||||
'<div class="vcs-fh">' +
|
||||
'<span class="vcs-caret"></span>' +
|
||||
'<span class="vcs-path">' + esc(f.path) + '</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>' +
|
||||
'</div>' +
|
||||
'<div class="vcs-fb"><div class="vcs-fb-in">' + patchHtml(f) + (f.truncated ? '<div class="vcs-nodiff">差异过大,已截断</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) {
|
||||
st.cur = d;
|
||||
const openAll = d.files.length <= 3; // 少量文件默认展开,多文件默认折叠
|
||||
const parts = [];
|
||||
parts.push('<div class="vcs-detail">');
|
||||
parts.push('<button type="button" class="vcs-back" data-act="back">返回提交列表</button>');
|
||||
if (d.commit) {
|
||||
parts.push('<div class="vcs-commit">' +
|
||||
'<div class="vcs-subject">' + esc(d.commit.subject) + '</div>' +
|
||||
'<div class="vcs-meta"><span>' + esc(d.commit.author) + '</span><span>' + esc(fmtTime(d.commit.time)) + '</span>' +
|
||||
'<span class="vcs-hash">' + esc(d.commit.short) + '</span>' +
|
||||
(d.commit.parents && d.commit.parents.length > 1 ? '<span>合并提交</span>' : '') + '</div>' +
|
||||
(d.commit.body ? '<pre class="vcs-msg">' + esc(d.commit.body) + '</pre>' : '') +
|
||||
'</div>');
|
||||
} else {
|
||||
parts.push('<div class="vcs-commit"><div class="vcs-subject">未提交的改动</div>' +
|
||||
'<div class="vcs-meta"><span>' + esc(d.repo.branch || 'HEAD') + '</span><span>' + esc(d.repo.root) + '</span></div></div>');
|
||||
}
|
||||
parts.push('<div class="vcs-sum">' + d.stats.files + ' 个文件 · <b class="a">+' + d.stats.adds + '</b> <b class="d">-' + d.stats.dels + '</b></div>');
|
||||
d.files.forEach(function (f, i) { parts.push(fileHtml(f, i, openAll)); });
|
||||
if (!d.files.length) parts.push('<div class="vcs-empty">没有文件变动</div>');
|
||||
parts.push('</div>');
|
||||
bodyEl().innerHTML = parts.join('');
|
||||
syncPatchWidth(bodyEl());
|
||||
}
|
||||
|
||||
// ---------- 数据加载 ----------
|
||||
async function loadList(more) {
|
||||
const seq = ++st.seq;
|
||||
const keepTop = more ? bodyEl().scrollTop : 0; // 加载更多是整体重绘,得自己把滚动位置补回去
|
||||
st.view = 'list';
|
||||
st.sid = sid();
|
||||
if (!more) { st.commits = []; st.next = null; bodyEl().innerHTML = '<div class="pv-loading"></div>'; }
|
||||
const q = '?limit=' + PAGE + (more && st.next ? '&before=' + encodeURIComponent(st.next) : '');
|
||||
let d;
|
||||
try { d = await api('/git/commits' + q); }
|
||||
catch (e) { if (seq === st.seq) errBox('请求失败:' + (e.message || e), function () { loadList(false); }); return; }
|
||||
if (seq !== st.seq) return;
|
||||
if (!d || !d.ok) { errBox(reasonText(d && d.reason), function () { loadList(false); }); return; }
|
||||
st.repo = d.repo;
|
||||
st.worktree = d.worktree;
|
||||
st.commits = more ? st.commits.concat(d.commits) : d.commits;
|
||||
st.next = d.next;
|
||||
setAddr(d.repo);
|
||||
renderList();
|
||||
if (more) bodyEl().scrollTop = keepTop;
|
||||
}
|
||||
|
||||
async function loadDetail(rev) {
|
||||
const seq = ++st.seq;
|
||||
st.view = rev === 'worktree' ? 'worktree' : 'detail';
|
||||
st.sid = sid();
|
||||
bodyEl().innerHTML = '<div class="pv-loading"></div>';
|
||||
let d;
|
||||
try { d = await api('/git/commit/' + encodeURIComponent(rev)); }
|
||||
catch (e) {
|
||||
if (seq === st.seq) errBox('请求失败:' + (e.message || e), function () { loadDetail(rev); });
|
||||
return;
|
||||
}
|
||||
if (seq !== st.seq) return;
|
||||
if (!d || !d.ok) { errBox(reasonText(d && d.reason), function () { loadDetail(rev); }); return; }
|
||||
renderDetail(d);
|
||||
}
|
||||
|
||||
function refresh() {
|
||||
if (st.view === 'list') return loadList(false);
|
||||
if (st.view === 'worktree') return loadDetail('worktree');
|
||||
if (st.cur && st.cur.commit) return loadDetail(st.cur.commit.id);
|
||||
return loadList(false);
|
||||
}
|
||||
|
||||
// ---------- 面板开关 ----------
|
||||
function syncBtn() {
|
||||
const b = document.getElementById('tree-vcs');
|
||||
if (b) b.classList.toggle('active', document.body.classList.contains('pv-mode-vcs'));
|
||||
}
|
||||
|
||||
function setMode(on) {
|
||||
document.body.classList.toggle('pv-mode-vcs', !!on);
|
||||
syncBtn();
|
||||
}
|
||||
|
||||
function openPane() {
|
||||
if (!sid()) { toast('请先打开一个会话'); return; }
|
||||
if (typeof pvDesktop === 'function' && !pvDesktop()) { toast('Git 面板仅在桌面端可用'); return; }
|
||||
const on = document.body.classList.contains('pv-mode-vcs');
|
||||
if (on && st.sid === sid()) { // 再点一次:有上次预览就切回预览,否则关面板
|
||||
setMode(false);
|
||||
if (st.lastPreview) { openFilePreview(st.lastPreview); return; }
|
||||
document.getElementById('pv-close').click();
|
||||
return;
|
||||
}
|
||||
if (!on) st.lastPreview = (typeof pvState === 'object' && pvState && pvState.name) || null;
|
||||
if (typeof pvOpenPane === 'function') pvOpenPane();
|
||||
setMode(true);
|
||||
pvClearBody();
|
||||
pvHeader(null); // 清掉预览的文件名与下载钮;地址条下面再写仓库路径
|
||||
pvToolbar({ refresh: true, popup: false, reload: refresh });
|
||||
loadList(false);
|
||||
}
|
||||
|
||||
// 事件委托:pv-body 的内容每次整体重建,逐元素绑定没必要
|
||||
document.getElementById('pv-body').addEventListener('click', function (e) {
|
||||
if (!document.body.classList.contains('pv-mode-vcs')) return;
|
||||
const it = e.target.closest('.vcs-item');
|
||||
if (it) {
|
||||
if (it.dataset.act === 'worktree') loadDetail('worktree');
|
||||
else if (it.dataset.act === 'commit') loadDetail(it.dataset.id);
|
||||
return;
|
||||
}
|
||||
const more = e.target.closest('.vcs-more');
|
||||
if (more) { loadList(true); return; }
|
||||
const back = e.target.closest('.vcs-back');
|
||||
if (back) { loadList(false); return; }
|
||||
const fh = e.target.closest('.vcs-fh');
|
||||
if (fh) { fh.parentNode.classList.toggle('open'); syncPatchWidth(fh.parentNode); return; }
|
||||
});
|
||||
|
||||
window.openVcsPane = openPane;
|
||||
window.vcsSetMode = setMode;
|
||||
window.vcsRefresh = refresh;
|
||||
})();
|
||||
@@ -36,6 +36,11 @@
|
||||
const MAX_MS = 180000; // 单次录音上限(流式上传后不再受 60s 限制)
|
||||
const MIN_MS = 500; // 短于这个时长按误触处理,不上传
|
||||
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 软切)并发就会很多,全放出去会把上游压垮、
|
||||
// 也可能被限流。超过就排到后面,等前面的落定再发。改完刷新页面即生效。
|
||||
const ASR_MAX_CONCURRENCY = 3;
|
||||
@@ -125,10 +130,14 @@
|
||||
// ---------- 遮罩 / 声波 ----------
|
||||
function setOverlayMode(m) { // 'send' | 'cancel' | 'busy'
|
||||
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) {
|
||||
hintEl.textContent = m === 'cancel' ? '松开取消'
|
||||
: m === 'busy' ? busyHintText() : '松手传送,上滑取消';
|
||||
hintEl.textContent = m === 'cancel' ? '松手取消'
|
||||
: m === 'busy' ? busyHintText()
|
||||
: (POINT_FINE ? '' : '松手传送,上滑取消');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -302,7 +311,7 @@
|
||||
abortStream();
|
||||
if (stopTimer) { clearTimeout(stopTimer); stopTimer = null; }
|
||||
hold.classList.remove('recording');
|
||||
setHoldText('按住 说话');
|
||||
setHoldText(HOLD_IDLE);
|
||||
hideOverlay();
|
||||
updateSendBtn();
|
||||
}
|
||||
@@ -344,7 +353,7 @@
|
||||
segSent = 0;
|
||||
segDone = 0;
|
||||
hold.classList.add('recording');
|
||||
setHoldText('松开 结束');
|
||||
setHoldText(HOLD_REC);
|
||||
showOverlay();
|
||||
|
||||
if (native) {
|
||||
@@ -413,7 +422,7 @@
|
||||
if (held < MIN_MS) discard = true;
|
||||
phase = 'busy';
|
||||
hold.classList.remove('recording');
|
||||
setHoldText(discard ? '按住 说话' : '正在识别…');
|
||||
setHoldText(discard ? HOLD_IDLE : '正在识别…');
|
||||
// 遮罩留着,文案换成动态识别进度;柱子停在低位,等结果回来再收
|
||||
setOverlayMode(discard ? 'send' : 'busy');
|
||||
stopMeter();
|
||||
@@ -464,15 +473,15 @@
|
||||
resetUI();
|
||||
}
|
||||
|
||||
// ---------- 按住 / 滑动 / 松开 ----------
|
||||
hold.addEventListener('pointerdown', function (e) {
|
||||
// ---------- 按住 / 滑动 / 松开(手机)或点击切换(桌面)----------
|
||||
function onPointerDown(e) {
|
||||
if (e && e.button != null && e.button !== 0) return; // 只响应左键/触摸
|
||||
e.preventDefault();
|
||||
if (phase !== 'idle') return;
|
||||
pressY = e.clientY || 0;
|
||||
try { hold.setPointerCapture(e.pointerId); } catch (_) { /* 忽略 */ }
|
||||
startHold();
|
||||
});
|
||||
}
|
||||
|
||||
function onMove(e) {
|
||||
if (!pressing) return;
|
||||
@@ -503,13 +512,39 @@
|
||||
else if (phase === 'arming') cancelHold(); // 还没真正开录:当误触
|
||||
}
|
||||
|
||||
hold.addEventListener('pointerup', onRelease);
|
||||
hold.addEventListener('pointercancel', onRelease);
|
||||
hold.addEventListener('pointermove', onMove);
|
||||
// 兜底:个别环境下 setPointerCapture 不生效,手指移出按钮后也要跟手
|
||||
window.addEventListener('pointerup', onRelease);
|
||||
window.addEventListener('pointercancel', onRelease);
|
||||
window.addEventListener('pointermove', onMove);
|
||||
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('pointercancel', onRelease);
|
||||
hold.addEventListener('pointermove', onMove);
|
||||
// 兜底:个别环境下 setPointerCapture 不生效,手指移出按钮后也要跟手
|
||||
window.addEventListener('pointerup', onRelease);
|
||||
window.addEventListener('pointercancel', onRelease);
|
||||
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(); });
|
||||
|
||||
+1
File diff suppressed because one or more lines are too long
@@ -47,9 +47,19 @@ router.use('/app', (req, res) => {
|
||||
if (!sessionId) return notFound(res, '会话不存在');
|
||||
if (!engine.getSession(sessionId)) return notFound(res, '会话不存在');
|
||||
const appRoot = path.join(engine.taskDirOf(sessionId), '.app');
|
||||
// 页面根目录的地址必须带尾斜杠:浏览器按「最后一段是否目录」算相对链接的基址,
|
||||
// /app/<会话> 会把 ./table.html 解析成 /app/table.html(白屏)。
|
||||
// 空余路径 = 就是在要根目录 → 补斜杠再跳转;比让每个技能模板改绝对链接可靠。
|
||||
// 注意不能靠 stat 判断:下面空余路径会先被映射成 index.html,永远不是目录。
|
||||
const rest = segs.slice(1).join('/');
|
||||
if (!rest && !req.path.endsWith('/')) {
|
||||
const q = req.originalUrl.indexOf('?');
|
||||
return res.redirect(302, (q < 0 ? req.originalUrl : req.originalUrl.slice(0, q)) + '/'
|
||||
+ (q < 0 ? '' : req.originalUrl.slice(q)));
|
||||
}
|
||||
let abs;
|
||||
try {
|
||||
abs = resolveInTask(appRoot, segs.slice(1).join('/') || 'index.html'); // 越界即挡,限 .app/ 子树
|
||||
abs = resolveInTask(appRoot, rest || 'index.html'); // 越界即挡,限 .app/ 子树
|
||||
} catch (_) {
|
||||
return notFound(res, '非法路径');
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ const { listTaskFiles } = require('./sessions');
|
||||
const { resolveInTask } = require('../tools/executor');
|
||||
const downloadToken = require('../download-token');
|
||||
const log = require('../log');
|
||||
const git = require('../git');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
@@ -76,6 +77,101 @@ router.post('/:id/files', upload.array('files', 10), function (req, res) {
|
||||
}
|
||||
});
|
||||
|
||||
// ---------- 会话文件树(桌面端左栏唯一浏览入口) ----------
|
||||
// 为什么不复用 GET /:id/files:那个接口同步递归整棵目录,会话里一旦有大项目 /
|
||||
// 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;
|
||||
|
||||
// 相对路径 → 会话根内的绝对路径。字面 + realpath 双重校验,防符号链接跳出会话目录。
|
||||
function resolveTreeAbs(rootAbs, rel) {
|
||||
const p = String(rel || '').replace(/^[\\/]+/, '');
|
||||
const abs = p ? path.resolve(rootAbs, p) : rootAbs;
|
||||
const inside = (root, x) => x === root || x.startsWith(root + path.sep);
|
||||
if (!inside(rootAbs, abs)) throw new Error('路径越界');
|
||||
let realAbs = abs, realRoot = rootAbs;
|
||||
try { realAbs = fs.realpathSync(abs); } catch (_) {}
|
||||
try { realRoot = fs.realpathSync(rootAbs); } catch (_) {}
|
||||
if (!inside(realRoot, realAbs)) throw new Error('路径越界');
|
||||
return abs;
|
||||
}
|
||||
|
||||
router.get('/:id/tree', function (req, res) {
|
||||
const session = engine.getSession(req.params.id);
|
||||
if (!session) return res.status(404).json({ error: '会话不存在' });
|
||||
const rootAbs = path.resolve(engine.taskDirOf(req.params.id));
|
||||
const rel = String(req.query.dir || '').replace(/^[\\/]+/, '').replace(/\/+$/, '');
|
||||
let abs;
|
||||
try { abs = resolveTreeAbs(rootAbs, rel); }
|
||||
catch (err) { return res.status(400).json({ error: err.message }); }
|
||||
let st;
|
||||
try { st = fs.statSync(abs); } catch (_) { return res.status(404).json({ error: '目录不存在' }); }
|
||||
if (!st.isDirectory()) return res.status(400).json({ error: '不是目录' });
|
||||
const showHidden = req.query.hidden === '1';
|
||||
const entries = [];
|
||||
try {
|
||||
for (const e of fs.readdirSync(abs, { withFileTypes: true })) {
|
||||
if (!showHidden && e.name.startsWith('.')) continue;
|
||||
const childRel = rel ? rel + '/' + e.name : e.name;
|
||||
if (e.isSymbolicLink()) { entries.push({ name: e.name, rel: childRel, type: 'link' }); continue; }
|
||||
if (e.isDirectory()) {
|
||||
// mtimeMs 给前端判断空目录是否还是空的:目录内增删子项会更新它
|
||||
let mtimeMs = null;
|
||||
try { mtimeMs = fs.statSync(path.join(abs, e.name)).mtimeMs; } catch (_) {}
|
||||
entries.push({ name: e.name, rel: childRel, type: 'dir', ignored: TREE_IGNORE_DIRS.has(e.name), mtimeMs: mtimeMs });
|
||||
} else if (e.isFile()) {
|
||||
let size = null;
|
||||
try { size = fs.statSync(path.join(abs, e.name)).size; } catch (_) {}
|
||||
entries.push({ name: e.name, rel: childRel, type: 'file', size: size });
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
return res.status(500).json({ error: String((err && err.message) || err) });
|
||||
}
|
||||
// 排序:正常目录 → 正常文件 → 被忽略的大目录(灰显沉底);同类按名称
|
||||
entries.sort((a, b) =>
|
||||
(a.ignored ? 1 : 0) - (b.ignored ? 1 : 0) ||
|
||||
(a.type === 'dir' ? 0 : 1) - (b.type === 'dir' ? 0 : 1) ||
|
||||
(a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
|
||||
res.json({
|
||||
root: rootAbs,
|
||||
dir: rel,
|
||||
total: entries.length,
|
||||
capped: entries.length > TREE_MAX,
|
||||
entries: entries.slice(0, TREE_MAX),
|
||||
});
|
||||
});
|
||||
|
||||
// ---------- Git 面板(只读):提交列表 / 提交详情 ----------
|
||||
// rev=worktree 是「未提交的改动」,与提交详情返回同一副骨架(commit=null),前端共用一个渲染器。
|
||||
// 不是仓库 / 没装 git 不算错误:HTTP 200 + { ok:false, reason },由界面显示空状态。
|
||||
function gitDir(req) { return engine.taskDirOf(req.params.id); }
|
||||
|
||||
router.get('/:id/git/commits', async function (req, res) {
|
||||
const session = engine.getSession(req.params.id);
|
||||
if (!session) return res.status(404).json({ error: '会话不存在' });
|
||||
const limit = Math.min(Math.max(parseInt(req.query.limit, 10) || 30, 1), 100);
|
||||
const before = String(req.query.before || '');
|
||||
// before 只接受完整/短 hash:它会拼进 git 参数,绝不能是任意表达式
|
||||
const out = await git.query(gitDir(req), 'commits', {
|
||||
before: /^[0-9a-f]{7,40}$/i.test(before) ? before : '',
|
||||
limit,
|
||||
});
|
||||
res.json(out);
|
||||
});
|
||||
|
||||
router.get('/:id/git/commit/:rev', async function (req, res) {
|
||||
const session = engine.getSession(req.params.id);
|
||||
if (!session) return res.status(404).json({ error: '会话不存在' });
|
||||
const rev = String(req.params.rev || '');
|
||||
if (rev !== 'worktree' && !/^[0-9a-f]{4,40}$/i.test(rev)) return res.status(400).json({ error: '非法的提交编号' });
|
||||
res.json(await git.query(gitDir(req), 'commit', { rev }));
|
||||
});
|
||||
|
||||
router.get('/:id/files', function (req, res) {
|
||||
try {
|
||||
const session = engine.getSession(req.params.id);
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
// 本地桌面端(local/ 启动器)专用:唤起系统原生目录选择器。
|
||||
// 只在 AGENT_LOCAL_PICK=1 时挂载(见 server.js),服务器形态根本不加载本文件。
|
||||
//
|
||||
// 为什么必须走后端:浏览器拿不到本机目录的绝对路径(<input webkitdirectory> 只给相对名),
|
||||
// 要真实路径只能调系统对话框。必须 execFile 异步——同步执行会阻塞事件循环,所有会话的 SSE
|
||||
// 都会卡住,直到用户关掉对话框。用户取消不是错误,回 { path: '' };
|
||||
// 其它失败(无对话框、权限被拒、超时)要带原因回给前端,别让用户以为是自己取消了。
|
||||
const express = require('express');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const os = require('os');
|
||||
const { execFile } = require('child_process');
|
||||
const engine = require('../engine');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
function sendErr(res, err) {
|
||||
const code = (err && err.status_code) || 500;
|
||||
res.status(code).json({ error: String((err && err.message) || err) });
|
||||
}
|
||||
|
||||
// 各平台可用的对话框后端。mac 用 osascript;Linux 依次试 zenity / kdialog。
|
||||
// cancelRe / cancelExit 区分「用户取消」和「真失败」:
|
||||
// osascript 取消时 stderr 是 "User canceled. (-128)",别的报错(如自动化权限被拒)不能当取消;
|
||||
// zenity/kdialog 取消统一退出码 1。
|
||||
const CANDIDATES = process.platform === 'darwin'
|
||||
? [{ cmd: 'osascript', args: ['-e', 'POSIX path of (choose folder with prompt "选择这个会话的工作目录")'], cancelRe: /User canceled|-128/ }]
|
||||
: process.platform === 'linux'
|
||||
? [
|
||||
{ cmd: 'zenity', args: ['--file-selection', '--directory', '--title=选择这个会话的工作目录'], cancelExit: 1 },
|
||||
{ cmd: 'kdialog', args: ['--getexistingdirectory', os.homedir(), '--title', '选择这个会话的工作目录'], cancelExit: 1 },
|
||||
]
|
||||
: [];
|
||||
|
||||
// 跑一个对话框,resolve 出选中的路径(用户取消 → '')。
|
||||
// 超时兜底:对话框可能被用户晾在那儿,这里到点 kill,避免永远挂着一个 child。
|
||||
function runPicker(cand, timeoutMs) {
|
||||
return new Promise((resolve, reject) => {
|
||||
execFile(cand.cmd, cand.args, { timeout: timeoutMs, maxBuffer: 1 << 20 }, (err, stdout, stderr) => {
|
||||
if (!err) return resolve(String(stdout || '').trim());
|
||||
if (err.code === 'ENOENT') return reject(Object.assign(new Error('no-cmd'), { no_cmd: true }));
|
||||
if (err.killed) return reject(Object.assign(new Error('选择目录超时,请重试'), { status_code: 408 }));
|
||||
const msg = String(stderr || '').trim();
|
||||
if (cand.cancelRe && cand.cancelRe.test(msg)) return resolve('');
|
||||
if (cand.cancelExit && err.code === cand.cancelExit) return resolve('');
|
||||
reject(Object.assign(new Error('目录选择器失败:' + (msg || ('退出码 ' + err.code))), { status_code: 500 }));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function pickDir() {
|
||||
if (!CANDIDATES.length) {
|
||||
throw Object.assign(new Error('当前系统不支持目录选择(仅支持 macOS / Linux)'), { status_code: 501 });
|
||||
}
|
||||
for (const cand of CANDIDATES) {
|
||||
try {
|
||||
const out = await runPicker(cand, 120000);
|
||||
if (!out) return '';
|
||||
// osascript 的 POSIX path 带尾斜杠,去掉让展示一致;选到根 '/' 时保底保留。
|
||||
return out.replace(/\/+$/, '') || '/';
|
||||
} catch (e) {
|
||||
if (e.no_cmd) continue; // 换下一个后端
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
throw Object.assign(new Error('没有可用的目录选择器(Linux 请安装 zenity 或 kdialog)'), { status_code: 501 });
|
||||
}
|
||||
|
||||
// ---------- 原生文件管理器(仅本机会话目录内) ----------
|
||||
// 文件树的列表接口已上收为通用的 GET /api/sessions/:id/tree(桌面端服务器形态也用),
|
||||
// 这里只剩「在 Finder / 终端中打开」这两个只能开在本机的动作。
|
||||
function isInside(rootAbs, abs) {
|
||||
return abs === rootAbs || abs.startsWith(rootAbs + path.sep);
|
||||
}
|
||||
|
||||
// 会话内相对路径 → 绝对路径,双重越界校验(字面 + realpath,防符号链接跳出)。
|
||||
function resolveInside(sessionId, rel) {
|
||||
const sid = String(sessionId || '').trim();
|
||||
if (!sid) throw Object.assign(new Error('缺少 session'), { status_code: 400 });
|
||||
const session = engine.getSession(sid);
|
||||
if (!session) throw Object.assign(new Error('会话不存在'), { status_code: 404 });
|
||||
const rootAbs = path.resolve(engine.taskDirOf(sid));
|
||||
const p = String(rel || '').replace(/^[\\/]+/, '');
|
||||
const abs = p ? path.resolve(rootAbs, p) : rootAbs;
|
||||
if (!isInside(rootAbs, abs)) throw Object.assign(new Error('路径越界'), { status_code: 400 });
|
||||
let real = abs, rootReal = rootAbs;
|
||||
try { real = fs.realpathSync(abs); } catch (_) {}
|
||||
try { rootReal = fs.realpathSync(rootAbs); } catch (_) {}
|
||||
if (!isInside(rootReal, real)) throw Object.assign(new Error('路径越界'), { status_code: 400 });
|
||||
return { rootAbs: rootAbs, abs: abs };
|
||||
}
|
||||
|
||||
// execFile 异步(同步会阻塞事件循环);open/xdg-open 一般秒回,10s 兜底。
|
||||
function runOpen(cmd, args) {
|
||||
return new Promise((resolve, reject) => {
|
||||
execFile(cmd, args, { timeout: 10000 }, (err) => {
|
||||
if (!err) return resolve();
|
||||
if (err.code === 'ENOENT') return reject(Object.assign(new Error('no-cmd'), { no_cmd: true }));
|
||||
if (err.killed) return reject(Object.assign(new Error('系统调用超时'), { status_code: 504 }));
|
||||
reject(Object.assign(new Error('打开失败:' + (err.message || err.code)), { status_code: 500 }));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function dirOf(abs) {
|
||||
try { return fs.statSync(abs).isDirectory() ? abs : path.dirname(abs); } catch (_) { return path.dirname(abs); }
|
||||
}
|
||||
|
||||
// 在系统文件管理器里打开:目录→直接打开;文件→定位所在目录(mac 用 open -R 直接选中该文件)。
|
||||
router.post('/reveal', (req, res) => {
|
||||
let target;
|
||||
try { target = resolveInside(req.body && req.body.session, req.body && req.body.path); }
|
||||
catch (err) { return sendErr(res, err); }
|
||||
const abs = target.abs;
|
||||
let isDir = false;
|
||||
try { isDir = fs.statSync(abs).isDirectory(); } catch (_) {}
|
||||
const mac = process.platform === 'darwin';
|
||||
const cmd = mac ? 'open' : 'xdg-open';
|
||||
const args = mac && !isDir ? ['-R', abs] : [isDir ? abs : path.dirname(abs)];
|
||||
runOpen(cmd, args).then(() => res.json({ ok: true })).catch(err => sendErr(res, err));
|
||||
});
|
||||
|
||||
// 在系统终端里打开该目录。mac 用 open -a Terminal;Linux 尽力而为。
|
||||
router.post('/terminal', (req, res) => {
|
||||
let target;
|
||||
try { target = resolveInside(req.body && req.body.session, req.body && req.body.path); }
|
||||
catch (err) { return sendErr(res, err); }
|
||||
const dir = dirOf(target.abs);
|
||||
if (process.platform === 'darwin') {
|
||||
runOpen('open', ['-a', 'Terminal', dir]).then(() => res.json({ ok: true })).catch(err => sendErr(res, err));
|
||||
return;
|
||||
}
|
||||
runOpen('x-terminal-emulator', ['--working-directory=' + dir])
|
||||
.then(() => res.json({ ok: true }))
|
||||
.catch(() => runOpen('gnome-terminal', ['--working-directory=' + dir])
|
||||
.then(() => res.json({ ok: true }))
|
||||
.catch(() => sendErr(res, Object.assign(new Error('没有可用的终端程序'), { status_code: 501 }))));
|
||||
});
|
||||
|
||||
// 能力探测:前端凭这个决定是否显示「工作目录」入口(拿不到就整条隐藏)。
|
||||
router.get('/info', (req, res) => {
|
||||
res.json({ enabled: true, platform: process.platform, workspace_root: engine.getConfig().workspace_root });
|
||||
});
|
||||
|
||||
router.post('/pick-dir', (req, res) => {
|
||||
pickDir().then(p => res.json({ path: p })).catch(err => sendErr(res, err));
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -84,7 +84,9 @@ router.post('/', wrap((req, res) => {
|
||||
const assistantType = String((req.body && req.body.assistant_type) || 'secretary').trim().slice(0, 32) || 'secretary';
|
||||
// 创建者取认证中间件的 req.user(不信客户端传参);未启用认证时为空串
|
||||
const user = String(req.user || '').trim().slice(0, 64);
|
||||
const session = engine.createSession(title, modelId, assistantType, user);
|
||||
// 手选工作目录(仅本地端前端会传,服务器前端从不带;不传/空串 = 老行为,见 engine.createSession)
|
||||
const workDir = String((req.body && req.body.work_dir) || '').trim();
|
||||
const session = engine.createSession(title, modelId, assistantType, user, workDir);
|
||||
log.info('task', (req.user || '-') + ' 新建任务 ' + session.id + '「' + (session.title || '未命名') + '」model=' + (modelId || '自动') + ' type=' + (session.assistant_type || 'secretary'));
|
||||
res.json(session);
|
||||
}));
|
||||
@@ -196,16 +198,16 @@ router.get('/:id', wrap((req, res) => {
|
||||
}
|
||||
}
|
||||
|
||||
const taskDir = engine.taskDirOf(session.id);
|
||||
// 定时任务状态(scheduler.js / schedule 工具;每会话至多一行,无则 null)。
|
||||
// 列表接口故意不带此字段,避免 N+1;前端进会话详情时才拉。
|
||||
const schedule = db.prepare(
|
||||
'SELECT cron_expr, prompt, next_run_at, last_run_at, last_status, last_note FROM scheduled_tasks WHERE session_id = ?'
|
||||
).get(session.id) || null;
|
||||
// 不再返回 files:文件树由 /api/files 按目录懒加载(routes/files.js),
|
||||
// 这里全量递归扫一遍纯属浪费——曾让每次切会话多传 1.4MB(10544 个文件)。
|
||||
res.json({
|
||||
session,
|
||||
messages,
|
||||
files: listTaskFiles(taskDir),
|
||||
schedule,
|
||||
running: !!(engine.getRun(session.id) || {}).looping,
|
||||
// 待投递队列(刷新/换设备后条幅能原样恢复):只在服务端内存里,重启即空
|
||||
|
||||
+25
-3
@@ -19,6 +19,11 @@ const log = require('./log');
|
||||
const cfg = loadConfig(process.env.AGENT_CONFIG);
|
||||
log.setLevel(cfg.log_level); // 分级日志开关(log.js;config.yml log_level,重启生效)
|
||||
llm.setPayloadTrim(cfg.agent); // 历史重放的重负载占位裁剪规则(llm.buildMessages;config agent.trim.rules)
|
||||
// system prompt 的「环境段」:executor.url 为空 = 命令在本机 spawn(本地桌面形态,无沙箱),
|
||||
// 有值 = 送进 agent-executor 容器(每会话隔离)。用这个信号而不是另立开关,因为它就是
|
||||
// 隔离与否的成因(resolveInTask 的 /tmp 重写、WIDE_SCOPE 同理)。启动日志跟一行,方便核对。
|
||||
llm.setEnvMode(cfg.executor.url ? 'server' : 'local');
|
||||
log.info('startup', '环境形态:' + (cfg.executor.url ? 'server(executor 容器隔离)' : 'local(本机 spawn,无沙箱)'));
|
||||
// 启动时把生效规则打出来:工具名拼错不会报错(MCP 工具要等发现后才存在),只能靠这行核对。
|
||||
log.info('startup', '历史重放占位裁剪:' + (((cfg.agent && cfg.agent.trim && cfg.agent.trim.rules) || [])
|
||||
.map(r => r.tool + '/' + r.side + '(轮≥' + r.rounds + ',回合≥' + r.turns + ')').join(', ') || '关闭'));
|
||||
@@ -67,6 +72,12 @@ require('./routes/preview-proxy').earlyGuard(app);
|
||||
|
||||
app.use(express.static(path.join(__dirname, 'public')));
|
||||
|
||||
// 本地桌面端(local/ 启动器)专用:原生目录选择器。AGENT_LOCAL_PICK=1 才挂,
|
||||
// 服务器形态零影响(不加载 routes/local.js,/api/local/* 一律 404)。
|
||||
if (String(process.env.AGENT_LOCAL_PICK || '') === '1') {
|
||||
app.use('/api/local', require('./routes/local'));
|
||||
}
|
||||
|
||||
app.use('/api/sessions', require('./routes/sessions'));
|
||||
app.use('/api/sessions', require('./routes/messages'));
|
||||
app.use('/api/sessions', require('./routes/files'));
|
||||
@@ -168,7 +179,16 @@ app.get('/api/health', (req, res) => {
|
||||
});
|
||||
});
|
||||
|
||||
// 统一错误出口:**必须最后挂**(Express 按注册顺序挑错误中间件,挂在路由前等于没挂)。
|
||||
// 没有它,任何路由漏出的异常(最典型:res.sendFile 的异步失败)都会落到 Express 默认
|
||||
// 处理器,在非 production 环境下把 err.stack 拼成 HTML 吐给请求方,泄露服务端绝对路径、
|
||||
// 源码行号与依赖版本——/p/<id> 是匿名可达端点,这份栈等于公开。详见 error-handler.js。
|
||||
app.use(require('./error-handler').errorHandler);
|
||||
|
||||
const PORT = process.env.PORT || cfg.port;
|
||||
// 监听地址:不设 = 0.0.0.0(容器/服务器形态,宿主机端口映射靠它)。
|
||||
// 本机 local 模式由 local/start.sh 注入 HOST=127.0.0.1:单机自用不该让同一局域网的人直接访问。
|
||||
const HOST = String(process.env.HOST || '').trim();
|
||||
|
||||
// 启动成功后把模型实际收到的各部分 dump 到文件方便人工核对(data_root 默认 ./data,
|
||||
// 宿主机对应 <repo>/data/prompt.txt,已被 gitignore)。包含:
|
||||
@@ -211,8 +231,8 @@ mcp.init(cfg).then(async () => {
|
||||
} catch (e) {
|
||||
log.warn('startup', '技能列表生成失败:' + e.message);
|
||||
}
|
||||
server.listen(PORT, () => {
|
||||
log.info('startup', 'Agent server listening on ' + PORT);
|
||||
const onListening = () => {
|
||||
log.info('startup', 'Agent server listening on ' + (HOST ? HOST + ':' : '') + PORT);
|
||||
log.info('startup', ' public_link=' + ((cfg.public_link || {}).base_url || '未配置(mint_public_link 不可用)'));
|
||||
log.info('startup', ' workspace_root=' + cfg.workspace_root);
|
||||
log.info('startup', ' data_root=' + cfg.data_root);
|
||||
@@ -231,7 +251,9 @@ mcp.init(cfg).then(async () => {
|
||||
} catch (e) {
|
||||
log.warn('startup', 'prompt dump 失败:' + e.message);
|
||||
}
|
||||
});
|
||||
};
|
||||
if (HOST) server.listen(PORT, HOST, onListening);
|
||||
else server.listen(PORT, onListening);
|
||||
});
|
||||
|
||||
// 优雅退出(照抄 executor/server.js 的 shutdown 形态):node 在容器里是 PID 1,
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
- You run on the user's own machine with their permissions, not a sandbox; other
|
||||
conversations share it and `/tmp` is the system temp dir. Work inside the
|
||||
working directory; treat everything outside it as the user's.
|
||||
- `python3` may be missing. Install what a task needs; Python packages go into
|
||||
`$AGENT_SKILLS_DEPS`. If a skill fails, cat its own `AGENTS.md`
|
||||
(`"$(dirname "$AGENT_SKILLS_DEPS")/<skill>/AGENTS.md"`) and follow it.
|
||||
- Installs and big downloads stay silent until they end. Run them in the background
|
||||
with output to a log file and poll that file every ~10s, instead of one long timeout.
|
||||
- Slow or failing installs and downloads: switch mirrors instead of retrying — pip
|
||||
`-i https://pypi.tuna.tsinghua.edu.cn/simple`, npm `--registry=https://registry.npmmirror.com`,
|
||||
GitHub URLs prefixed with `https://gh-proxy.com/`, Homebrew mirrors or let the user install.
|
||||
@@ -0,0 +1,16 @@
|
||||
- Linux container, isolated per conversation: you see the working directory, a
|
||||
session-scoped `/tmp`, read-only `/workspace/skills`, and system paths — never
|
||||
other sessions.
|
||||
- `terminal` runs POSIX sh (`/bin/sh` is dash); use `bash` for scripts.
|
||||
- `/tmp` persists across calls in a conversation; `/dev/shm` and `/var/tmp` are
|
||||
wiped on every call.
|
||||
- Python 3.11; system packages are read-only. Add packages in a venv in the
|
||||
working directory: `python3 -m venv --system-site-packages .venv`, then
|
||||
`.venv/bin/pip` / `.venv/bin/python`. Don't reinstall packages that are
|
||||
already importable.
|
||||
- System packages can't be installed at runtime (`apt-get` fails). A missing CLI
|
||||
tool must be added on the server — tell the user.
|
||||
- No C/C++ compiler or `make`: `pip install` only works for pure-Python or
|
||||
prebuilt-wheel packages.
|
||||
- Chinese text in matplotlib: set `font.sans-serif` to `Noto Sans CJK SC`. For
|
||||
ZIPs with GBK filenames, use `unar` or `7z x` to avoid garbled names.
|
||||
@@ -56,19 +56,4 @@ domain must never be hand-rolled.
|
||||
|
||||
## Environment
|
||||
|
||||
- Linux container, isolated per conversation: you see the working directory, a
|
||||
session-scoped `/tmp`, read-only `/workspace/skills`, and system paths — never
|
||||
other sessions.
|
||||
- `terminal` runs POSIX sh (`/bin/sh` is dash); use `bash` for scripts.
|
||||
- `/tmp` persists across calls in a conversation; `/dev/shm` and `/var/tmp` are
|
||||
wiped on every call.
|
||||
- Python 3.11; system packages are read-only. Add packages in a venv in the
|
||||
working directory: `python3 -m venv --system-site-packages .venv`, then
|
||||
`.venv/bin/pip` / `.venv/bin/python`. Don't reinstall packages that are
|
||||
already importable.
|
||||
- System packages can't be installed at runtime (`apt-get` fails). A missing CLI
|
||||
tool must be added on the server — tell the user.
|
||||
- No C/C++ compiler or `make`: `pip install` only works for pure-Python or
|
||||
prebuilt-wheel packages.
|
||||
- Chinese text in matplotlib: set `font.sans-serif` to `Noto Sans CJK SC`. For
|
||||
ZIPs with GBK filenames, use `unar` or `7z x` to avoid garbled names.
|
||||
{APP_ENV_SECTION}
|
||||
|
||||
@@ -19,30 +19,65 @@ const memory = require('../memory'); // recall 工具的数据面(日记翻阅
|
||||
const BUILTIN_TOOL_DEFS = require('./definitions.json');
|
||||
|
||||
// ---------- 路径沙箱 ----------
|
||||
function resolveInTask(taskDir, p) {
|
||||
// 文件工具的可见范围(AGENT_FILE_SCOPE,默认 session):
|
||||
// session = 锁在会话目录。与 executor 容器里的物理视图一致,是服务器形态。
|
||||
// workspace= 放宽到 workspace_root。本地桌面端形态(不起 executor、单机单用户):
|
||||
// AI 要能操作你指定的整个工作目录,而不是它的一个子目录。
|
||||
// 纯 env 接线与 EXECUTOR_URL/ASR_URL 同类:这是部署形态,不是平台配置。
|
||||
const WIDE_SCOPE = String(process.env.AGENT_FILE_SCOPE || '').trim().toLowerCase() === 'workspace';
|
||||
|
||||
function resolveInTask(taskDir, p, rootDir) {
|
||||
if (typeof p !== 'string' || !p.trim()) throw new Error('路径不能为空');
|
||||
const taskRoot = path.resolve(taskDir);
|
||||
let abs;
|
||||
if (path.isAbsolute(p)) {
|
||||
abs = path.normalize(p);
|
||||
// /tmp → <taskDir>/.tmp:与 executor 容器的 bind 对齐(容器内 /tmp 即会话 .tmp,
|
||||
// terminal 写 /tmp/x,core 侧实体在 <taskDir>/.tmp/x)。先 normalize 再重写,
|
||||
// 重写后仍走下方越界校验,无穿越风险。
|
||||
if (abs === '/tmp') abs = path.join(path.resolve(taskDir), '.tmp');
|
||||
else if (abs.startsWith('/tmp/')) abs = path.join(path.resolve(taskDir), '.tmp', abs.slice(5));
|
||||
// workspace 形态【不重写】:本地 terminal 是真 spawn,写的就是本机 /tmp,
|
||||
// 两边必须指向同一处——否则 AI 自己刚写到 /tmp 的文件,自己 read_file 读不到。
|
||||
if (!WIDE_SCOPE) {
|
||||
if (abs === '/tmp') abs = path.join(taskRoot, '.tmp');
|
||||
else if (abs.startsWith('/tmp/')) abs = path.join(taskRoot, '.tmp', abs.slice(5));
|
||||
}
|
||||
} else {
|
||||
abs = path.resolve(taskDir, p);
|
||||
// 相对路径永远相对会话目录(AI 的 cwd 就在那里),不随 rootDir 漂移。
|
||||
abs = path.resolve(taskRoot, p);
|
||||
}
|
||||
const root = path.resolve(taskDir);
|
||||
if (abs !== root && !abs.startsWith(root + path.sep)) {
|
||||
throw new Error('路径越界(只允许任务目录内操作):' + p);
|
||||
const root = path.resolve(rootDir || taskRoot);
|
||||
const inRoot = abs === root || abs.startsWith(root + path.sep);
|
||||
// workspace 形态额外放行本机 /tmp:AI 与 terminal 共用的临时区。
|
||||
const inTmp = WIDE_SCOPE && (abs === '/tmp' || abs.startsWith('/tmp/'));
|
||||
if (!inRoot && !inTmp) {
|
||||
throw new Error((rootDir ? '路径越界(只允许工作目录内操作):' : '路径越界(只允许任务目录内操作):') + p);
|
||||
}
|
||||
return abs;
|
||||
}
|
||||
|
||||
// 工具层允许的根:session 形态 = 会话目录;workspace 形态 = workspace_root。
|
||||
// 只给「业务工具」用;路由层(文件 API/公网短链/data-page)与 @历史会话仍按会话目录校验。
|
||||
function fsRoot(ctx) {
|
||||
// 手选工作目录的会话:AI 的一切文件操作都在这个真实目录里(本地端,不建 task-* 子目录)。
|
||||
// 优先于 WIDE_SCOPE 的 workspace_root 兜底。
|
||||
if (ctx.workDir) return ctx.workDir;
|
||||
if (!WIDE_SCOPE) return ctx.taskDir;
|
||||
return (ctx.cfg && ctx.cfg.workspace_root) || ctx.taskDir;
|
||||
}
|
||||
|
||||
function relOf(taskDir, abs) {
|
||||
return path.relative(path.resolve(taskDir), abs) || '.';
|
||||
}
|
||||
|
||||
// 展示用路径:会话目录内保持相对(跟以前一致,省 token);
|
||||
// 宽根模式下文件可能在会话目录外,那就回绝对路径——否则模型看到的是
|
||||
// ../../../../tmp/x 这种既难读、又容易被它当成会话内路径去二次拼接的名字。
|
||||
function dispPath(ctx, abs) {
|
||||
const rel = relOf(ctx.taskDir, abs);
|
||||
if (rel === '..' || rel.startsWith('..' + path.sep)) return abs;
|
||||
return rel;
|
||||
}
|
||||
|
||||
// ---------- 跨会话路径:@<会话id>/<rel>(历史只读,「看一眼」可过墙,「字节落地」只走 copy_path) ----------
|
||||
// 背景:terminal 在远端 executor 容器里跑(compose:wrapper 启动即 unmount host-tasks),
|
||||
// 别的会话目录在 shell 物理视图里根本不存在;core 进程内的文件工具又被 resolveInTask
|
||||
@@ -58,13 +93,15 @@ function resolvePastPath(ctx, p) {
|
||||
const sid = m[1];
|
||||
const rel = m[2] || '.';
|
||||
if (!/^task-[0-9A-Za-z_\-]+$/.test(sid)) throw new Error('@ 后需会话 id, 形如 task-YYYYMMDD-NNN: ' + sid);
|
||||
const s = ctx.db.prepare('SELECT id, user, title FROM sessions WHERE id = ?').get(sid);
|
||||
const s = ctx.db.prepare('SELECT id, user, title, work_dir FROM sessions WHERE id = ?').get(sid);
|
||||
if (!s) throw new Error('会话不存在: ' + sid);
|
||||
const me = ctx.db.prepare('SELECT user FROM sessions WHERE id = ?').get(ctx.sessionId);
|
||||
if (String(s.user || '') !== String((me && me.user) || '')) throw new Error('无权访问该会话: ' + sid);
|
||||
// 目标会话若手选了工作目录,@<会话> 也必须指向那个真实目录,而不是 workspace_root/<id>。
|
||||
const wd = String(s.work_dir || '');
|
||||
const root = String((ctx.cfg && ctx.cfg.workspace_root) || '');
|
||||
if (!root) throw new Error('workspace_root 未配置');
|
||||
const dir = path.join(root, sid);
|
||||
const dir = wd || (root ? path.join(root, sid) : '');
|
||||
if (!dir) throw new Error('workspace_root 未配置');
|
||||
return { sid: sid, title: s.title || sid, dir: dir, abs: resolveInTask(dir, rel) };
|
||||
}
|
||||
|
||||
@@ -284,7 +321,7 @@ async function toolReadFile(ctx, args) {
|
||||
const inner = relOf(past.dir, abs);
|
||||
disp = inner === '.' ? '@' + past.sid : '@' + past.sid + '/' + inner;
|
||||
} else {
|
||||
abs = resolveInTask(ctx.taskDir, args.path);
|
||||
abs = resolveInTask(ctx.taskDir, args.path, fsRoot(ctx));
|
||||
// 本会话沿用绝对路径做展示(大纲/首 1KB 头,历史行为不变);历史会话只暴露 @<sid>/<rel> 形,
|
||||
// 不把别的会话的 workspace_root 绝对路径喂进上下文。
|
||||
disp = abs;
|
||||
@@ -370,7 +407,7 @@ async function toolListDirectory(ctx, args) {
|
||||
const inner = relOf(past.dir, abs);
|
||||
prefix = '@' + past.sid + (inner === '.' ? '/' : '/' + inner + '/');
|
||||
} else {
|
||||
abs = resolveInTask(ctx.taskDir, p || '.');
|
||||
abs = resolveInTask(ctx.taskDir, p || '.', fsRoot(ctx));
|
||||
const inner = relOf(ctx.taskDir, abs);
|
||||
prefix = inner === '.' ? '' : inner + '/';
|
||||
}
|
||||
@@ -408,14 +445,15 @@ async function toolCopyPath(ctx, args) {
|
||||
const dp = String(args.destination_path || '').trim();
|
||||
if (!sp || !dp) throw new Error('source_path 与 destination_path 都必填');
|
||||
if (dp.startsWith('@')) throw new Error('destination_path 不支持 @ (历史只读)');
|
||||
const dst = resolveInTask(ctx.taskDir, dp);
|
||||
if (path.resolve(dst) === path.resolve(ctx.taskDir)) throw new Error('destination_path 不能是任务目录本身');
|
||||
const root = fsRoot(ctx);
|
||||
const dst = resolveInTask(ctx.taskDir, dp, root);
|
||||
if (path.resolve(dst) === path.resolve(root)) throw new Error('destination_path 不能是任务目录本身');
|
||||
let src;
|
||||
if (sp.startsWith('@')) {
|
||||
const past = resolvePastPath(ctx, sp);
|
||||
src = past.abs;
|
||||
} else {
|
||||
src = resolveInTask(ctx.taskDir, sp);
|
||||
src = resolveInTask(ctx.taskDir, sp, root);
|
||||
}
|
||||
if (path.resolve(src) === path.resolve(dst)) throw new Error('源与目标相同');
|
||||
let lst;
|
||||
@@ -435,17 +473,17 @@ async function toolCopyPath(ctx, args) {
|
||||
}
|
||||
let exists = true;
|
||||
try { await fsp.stat(dst); } catch (_) { exists = false; }
|
||||
if (exists) throw new Error('目标已存在, 拒绝覆盖: ' + relOf(ctx.taskDir, dst));
|
||||
if (exists) throw new Error('目标已存在, 拒绝覆盖: ' + dispPath(ctx, dst));
|
||||
await fsp.mkdir(path.dirname(dst), { recursive: true });
|
||||
await fsp.cp(src, dst, { recursive: true });
|
||||
recordFile(ctx, dst); // 文件表只记普通文件(目录自然跳过),供前端/微信附件展示
|
||||
const sizeNote = budget ? ' (' + budget.files + ' files, ' + Math.round(budget.bytes / 1024) + ' KB)' : '';
|
||||
return '已复制 ' + sp + ' -> ' + relOf(ctx.taskDir, dst) + sizeNote;
|
||||
return '已复制 ' + sp + ' -> ' + dispPath(ctx, dst) + sizeNote;
|
||||
}
|
||||
|
||||
async function toolWriteFile(ctx, args) {
|
||||
if (String(args.path || '').trim().startsWith('@')) throw new Error('write_file 不支持 @ 路径(历史只读;要改旧成果先 copy_path 导入本会话)');
|
||||
const abs = resolveInTask(ctx.taskDir, args.path);
|
||||
const abs = resolveInTask(ctx.taskDir, args.path, fsRoot(ctx));
|
||||
// 纵深防御:引擎 checkToolArgs 已把 null 判缺,但直调 executor(测试等)不经过它;
|
||||
// 旧版 `?? ''` 会把 null 洗成空串静默清空已有文件,这里显式拒绝。
|
||||
if (args.content == null) throw new Error('write_file 缺少参数 content(写空文件请显式传空字符串 "")');
|
||||
@@ -456,7 +494,7 @@ async function toolWriteFile(ctx, args) {
|
||||
await fsp.writeFile(abs, String(args.content), 'utf8');
|
||||
recordFile(ctx, abs);
|
||||
const nbytes = Buffer.byteLength(String(args.content), 'utf8');
|
||||
const rel = relOf(ctx.taskDir, abs);
|
||||
const rel = dispPath(ctx, abs);
|
||||
// 区分新建/覆盖:「原 M 字节」是给模型的止损信号(盲覆盖大文件时能立刻察觉)。
|
||||
return st
|
||||
? '已覆盖文件 ' + rel + '(' + nbytes + ' 字节,原 ' + st.size + ' 字节)'
|
||||
@@ -686,7 +724,7 @@ function applyEdit(text, edit, i) {
|
||||
// 错误信息告知模型已应用了多少、需重新 read_file。
|
||||
async function toolEditFile(ctx, args) {
|
||||
if (String(args.path || '').trim().startsWith('@')) throw new Error('edit_file 不支持 @ 路径(历史只读;要改旧成果先 copy_path 导入本会话)');
|
||||
const abs = resolveInTask(ctx.taskDir, args.path);
|
||||
const abs = resolveInTask(ctx.taskDir, args.path, fsRoot(ctx));
|
||||
let st;
|
||||
try { st = await fsp.stat(abs); }
|
||||
catch (_) { throw new Error('文件不存在:' + args.path); }
|
||||
@@ -711,7 +749,7 @@ async function toolEditFile(ctx, args) {
|
||||
? '(前 ' + applied + ' 处编辑已应用并保存,文件已变化,请重新 read_file 后再继续)'
|
||||
: '(文件未改动)'));
|
||||
}
|
||||
return '已成功应用 ' + applied + ' 处编辑到 ' + relOf(ctx.taskDir, abs);
|
||||
return '已成功应用 ' + applied + ' 处编辑到 ' + dispPath(ctx, abs);
|
||||
}
|
||||
|
||||
// 对齐 Zed select_terminal_output_lines:head/tail 各自取行;同时给时中间空一行;不去重叠;0 合法。
|
||||
@@ -751,7 +789,7 @@ async function toolTerminal(ctx, args) {
|
||||
const timeout = args.timeout_ms || cfg.terminal.default_timeout_ms;
|
||||
const maxChars = cfg.terminal.max_output_chars;
|
||||
let cwd = ctx.taskDir;
|
||||
if (args.cd) cwd = resolveInTask(ctx.taskDir, args.cd);
|
||||
if (args.cd) cwd = resolveInTask(ctx.taskDir, args.cd, fsRoot(ctx));
|
||||
if (!fs.existsSync(cwd)) throw new Error('工作目录不存在:' + cwd);
|
||||
|
||||
// 配了 executor.url(或 env EXECUTOR_URL):命令交给远端 agent-executor 执行,文本拼回与本地完全一致。
|
||||
@@ -1166,9 +1204,13 @@ function recordFile(ctx, abs) {
|
||||
try {
|
||||
const st = fs.statSync(abs);
|
||||
if (!st.isFile()) return;
|
||||
// 宽根模式(本地)下写在会话目录之外的文件不进附件表:表里的 filename 是会话相对路径,
|
||||
// 存个 '../x' 会让前端按会话去取,最终只能拿到 400。
|
||||
const rel = relOf(ctx.taskDir, abs);
|
||||
if (rel === '..' || rel.startsWith('..' + path.sep)) return;
|
||||
ctx.db.prepare(
|
||||
'INSERT INTO files (session_id, filename, size, created_at) VALUES (?,?,?,?)'
|
||||
).run(ctx.sessionId, relOf(ctx.taskDir, abs), st.size, Date.now());
|
||||
).run(ctx.sessionId, rel, st.size, Date.now());
|
||||
} catch (_) { /* 文件表仅用于展示,失败不影响主流程 */ }
|
||||
}
|
||||
|
||||
@@ -1177,7 +1219,11 @@ function recordFile(ctx, abs) {
|
||||
// 而 ctx.taskDir 就是会话目录,relOf 的结果正是取用侧(routes/public-files.js)要的 rel。
|
||||
async function toolMintPublicLink(ctx, args) {
|
||||
const pl = (ctx.cfg && ctx.cfg.public_link) || {};
|
||||
if (!pl.base_url) throw new Error('public_link.base_url 未配置,无法签发公网链接');
|
||||
// 本地桌面形态没有公网前缀,但用户就在这台机器上:回环地址签出来的链接照样点得开。
|
||||
// 与 visit_url 的回落同源(都不写配置,靠 HOST 判断形态);容器/服务器形态 HOST 为空
|
||||
// → localOrigin 返回 '' → 仍是原来那句报错,行为不变。
|
||||
const base = String(pl.base_url || '').replace(/\/+$/, '') || localOrigin(ctx.cfg);
|
||||
if (!base) throw new Error('public_link.base_url 未配置,无法签发公网链接');
|
||||
const abs = resolveInTask(ctx.taskDir, args.path);
|
||||
const rel = relOf(ctx.taskDir, abs);
|
||||
if (rel === '.') throw new Error('path 要指向一个文件,不能是任务目录本身');
|
||||
@@ -1191,7 +1237,7 @@ async function toolMintPublicLink(ctx, args) {
|
||||
throw new Error('path 经符号链接指向了任务目录之外,拒绝签发');
|
||||
}
|
||||
const id = publicFiles.mint({ sessionId: ctx.sessionId, rel, ttlMs: pl.ttl_ms });
|
||||
return pl.base_url + '/p/' + id;
|
||||
return base + '/p/' + id;
|
||||
}
|
||||
|
||||
// schedule:用户全部定时任务的生命周期(op 分派,规范见 docs/tool-design.md)。
|
||||
@@ -1577,6 +1623,15 @@ function toolDb(ctx, args) {
|
||||
// visit_url(front matter 可选):页面产物类技能声明访问路径模板,run 成功后在本层拼
|
||||
// public_link.base_url(与 mint_public_link 同源)追加完整「访问地址」——技能进程跑在
|
||||
// executor 隔离视图里不知道公网前缀,AI 拿到相对路径就会原样转给用户,而相对路径打不开。
|
||||
// 本地桌面形态的对外前缀:只有监听在回环地址(local/start.sh 注入 HOST=127.0.0.1)才认。
|
||||
// 容器/服务器形态 HOST 为空(= 0.0.0.0),不能凭空造一个 127.0.0.1 给远端用户,照旧只给站内路径。
|
||||
function localOrigin(cfg) {
|
||||
const host = String(process.env.HOST || '').trim().toLowerCase();
|
||||
if (host !== '127.0.0.1' && host !== 'localhost' && host !== '::1') return '';
|
||||
const port = String(process.env.PORT || (cfg && cfg.port) || '').trim();
|
||||
return port ? 'http://127.0.0.1:' + port : '';
|
||||
}
|
||||
|
||||
async function runSkillWithVisit(ctx, name, inputArgs) {
|
||||
const out = await skills.runSkill(ctx, name, inputArgs);
|
||||
let fm;
|
||||
@@ -1590,9 +1645,11 @@ async function runSkillWithVisit(ctx, name, inputArgs) {
|
||||
const rel = tpl.replace(/\{task_id\}/g, ctx.sessionId || path.basename(path.resolve(ctx.taskDir || '')));
|
||||
const pl = (ctx.cfg && ctx.cfg.public_link) || {};
|
||||
const base = String(pl.base_url || '').trim().replace(/\/+$/, '');
|
||||
return out + '\n访问地址:' + (base
|
||||
? base + rel
|
||||
: rel + '(站内路径:public_link.base_url 未配置,拼不出公网前缀)');
|
||||
if (base) return out + '\n访问地址:' + base + rel;
|
||||
// 没有公网前缀时别只给站内路径:本地形态用户就在这台机器上,回环地址就是能直接点开的地址。
|
||||
const origin = localOrigin(ctx.cfg);
|
||||
if (origin) return out + '\n访问地址:' + origin + rel;
|
||||
return out + '\n访问地址:' + rel + '(站内路径:public_link.base_url 未配置,拼不出公网前缀)';
|
||||
}
|
||||
|
||||
const SKILL_USAGE = 'skill 用法:{"op":"list"} / {"op":"get","name":"<技能名>"} / {"op":"run","name":"<技能名>","args":{...}}';
|
||||
@@ -1700,7 +1757,7 @@ function toolRecall(ctx, args) {
|
||||
case 'search': {
|
||||
const q = String(args.query || '').trim();
|
||||
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 + '」相关记录。';
|
||||
}
|
||||
case 'days': {
|
||||
@@ -1741,6 +1798,8 @@ const HANDLERS = {
|
||||
// (见 imageReceipt),image_rel 缺省表示本次不投递像素。
|
||||
// 内置工具优先;未命中时交给 MCP 注册表(启动时发现的服务工具)。
|
||||
async function executeTool(baseCtx, name, args) {
|
||||
// 会话目录懒建:会话创建时不再占坑,第一次真用到工具才建(纯文本对话不留空目录)。
|
||||
try { if (baseCtx && baseCtx.taskDir) fs.mkdirSync(baseCtx.taskDir, { recursive: true }); } catch (_) {}
|
||||
const handler = HANDLERS[name];
|
||||
if (handler) return handler(baseCtx, args || {});
|
||||
if (mcp.hasTool(name)) return mcp.callTool(name, args || {}, baseCtx); // baseCtx.taskDir → X-Session-Dir 头下发给 MCP 服务
|
||||
|
||||
@@ -280,10 +280,10 @@ async function runSkill(ctx, skillName, inputArgs) {
|
||||
throw new SkillExecutionError('技能 ' + skillName + ' 缺少入口 run.py 或 run.sh', 1);
|
||||
}
|
||||
|
||||
// cwd:远端取会话目录(executor 侧命中 session 隔离,技能看到的 /workspace/tasks/<sid>
|
||||
// 与 core 侧是同一份数据,absolutizeArgs 产出的绝对路径因此有效);缺 taskDir 时退回
|
||||
// 技能目录(退化为旧行为)。本地无隔离诉求,仍以技能目录为 cwd。
|
||||
const execCwd = rexec.isRemote(ctx.cfg) ? (ctx.taskDir || dir) : dir;
|
||||
// cwd 一律取会话任务目录(技能契约,见 skills/README §6:技能按 cwd 读写会话数据,
|
||||
// data-page 这类会往 cwd 下写 .app/)。旧代码在「无 executor」分支退回技能目录,
|
||||
// 等于假设线上一定走远端;本地桌面形态(本机 spawn)下会把所有按 cwd 干活的技能打歪。
|
||||
const execCwd = ctx.taskDir || dir;
|
||||
const timeoutMs = (ctx.cfg && ctx.cfg.skills && ctx.cfg.skills.timeout_ms) || 120000;
|
||||
log.info('skills', '执行 ' + skillName + ':' + entry + ' ' + cmdArgs.join(' ') + '(cwd=' + execCwd + ')');
|
||||
return runEntry(ctx, entry, cmdArgs, execCwd, timeoutMs);
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 257 KiB |
@@ -0,0 +1,484 @@
|
||||
# 本地端(local 模式):设计与交接
|
||||
|
||||
> 本文是 `local/` 的设计说明 + 交接单。
|
||||
> **状态:已在 macOS 真机(12.7.6 / x86_64 / Node 22.21 / python3 3.10,本机无 ffmpeg)按第 6 节
|
||||
> 清单逐项跑过,结果见第 5 节。** 只剩三件依赖人工交互或外部环境的事没覆盖(真实选目录弹窗、
|
||||
> 真浏览器打开、装 ffmpeg 之后的链路),见第 6 节。
|
||||
|
||||
## 1. 目标
|
||||
|
||||
把同一个 `agent-core` 直接跑在本机(macOS / Linux),**不装 Docker、不起 executor**,形态类似
|
||||
桌面 agent:给它一个工作目录,它在这个目录下的 `tasks/` 里放开手脚干活(`data/`、`skills/` 是兄弟目录,
|
||||
归启动器和技能自己管)。
|
||||
|
||||
明确的设计约束(都来自讨论):
|
||||
|
||||
- **和服务器端同一份代码**,不 fork 新仓库、不长期开 branch;靠运行时开关分叉
|
||||
- **`app/` 最小化改动**(最终只有 2 个后端文件,前端 0 改动)
|
||||
- **组件按需**:node 必需;ffmpeg 决定语音;python3 决定 Python 类技能能否执行(非 Python 技能如 `office` 不受影响)
|
||||
- **Windows 暂时不做**(本机执行依赖 POSIX 语义,见第 7 节)
|
||||
- 不用 Docker(用户明确否决)
|
||||
|
||||
基线版本:`v2.5.0`(服务器端最后一个纯容器部署版本)。
|
||||
|
||||
## 2. 与服务器形态的差异(只有六处)
|
||||
|
||||
| 差异 | 服务器 | 本地 | 由谁注入 |
|
||||
|---|---|---|---|
|
||||
| 命令在哪跑 | `agent-executor` 容器(mount/pid namespace 隔离) | 本机 `spawn`(**无沙箱**) | `EXECUTOR_URL` 留空 → 现成分支,未改代码 |
|
||||
| 文件工具的根 | 会话目录 `tasks/<会话id>/` | 工作目录下的 `tasks/`(`data/`、`skills/` 是兄弟目录,越界) | `AGENT_FILE_SCOPE=workspace` |
|
||||
| 监听地址 | `0.0.0.0` | `127.0.0.1` | `HOST=127.0.0.1` |
|
||||
| 对外链接(`mint_public_link` / `visit_url`) | `public_link.base_url` 拼公网短链 | 没有公网前缀时改拼 `http://127.0.0.1:<PORT>/p/<id>` | 复用 `localOrigin()`,靠 `HOST` 判断形态,不写配置 |
|
||||
| 读图回传给模型 | 签公网短链,上游服务器来拉 | 上游拉不到回环地址,改为内联 base64 `data:` URL | `AGENT_IMAGE_INLINE=1` |
|
||||
| office 预览的后端 | executor 的 `:3100` 网关(mount/pid 牢笼) | `local/preview-gateway.js`(同机、无牢笼) | `PREVIEW_PROXIES` 注入 core 的反代注册表 |
|
||||
|
||||
后五项都由本地启动器注入。**都不注入时,行为与 v2.5.0 完全一致**(容器部署不受影响)。
|
||||
|
||||
## 3. 本次改动清单
|
||||
|
||||
### 后端(`app/`)
|
||||
|
||||
| 文件 | 改动 |
|
||||
|---|---|
|
||||
| `app/server/server.js` | 读 `HOST` 环境变量;有值则 `server.listen(PORT, HOST, cb)`,无值维持 `listen(PORT, cb)`(= `0.0.0.0`)。启动日志带上 host |
|
||||
| `app/server/tools/executor.js` | 新增 `WIDE_SCOPE`(由 `AGENT_FILE_SCOPE=workspace` 打开)与 `fsRoot(ctx)`;`resolveInTask()` 增加可选第三参 `rootDir`;6 个业务工具的调用点改为传 `fsRoot(ctx)`;`recordFile()` 跳过会话目录之外的文件;`mint_public_link` 在没有 `public_link.base_url` 时改用 `localOrigin()`(回环地址) |
|
||||
| `app/server/engine.js` | `mintImageUrl` 在没有 `public_link.base_url` 且 `AGENT_IMAGE_INLINE=1` 时,把待回传的图内联成 `data:` URL(先做同样的 realpath 越界复核;>1.5MB 仍降级) |
|
||||
| `app/server/routes/files.js` | 新增 `GET /:id/tree`(桌面端左栏文件树用:单层懒加载、忽略大目录、上限 500、越界双重校验) |
|
||||
|
||||
`resolveInTask` 的两个分叉点:
|
||||
|
||||
1. **根**:`rootDir` 给了就按它校验(workspace 形态 = `workspace_root`),否则仍按会话目录
|
||||
2. **`/tmp`**:`session` 形态保持「重定向到 `<会话>/.tmp`」;`workspace` 形态**不重定向**,并把真实
|
||||
`/tmp` 纳入允许范围
|
||||
|
||||
### 刻意没有动的(重要)
|
||||
|
||||
- `resolvePastPath()`(`@<会话id>/...` 跨会话只读)—— 仍锁在对方会话目录
|
||||
- `routes/public-files.js`、`routes/data-page.js` —— 公网短链与 data-page 仍按会话目录校验
|
||||
- `mint_public_link` —— 路径校验仍是会话目录语义;只是没有公网前缀时改用回环地址签发(见 §2)
|
||||
- 前端 —— 本地模式没有专属前端代码;左栏文件树是桌面端共用的(见下)
|
||||
|
||||
> 追加:文件树最初只给 local 用,后来上收为桌面端通用能力 —— `/tree` 移到 `routes/files.js`,
|
||||
> 服务器形态的桌面端也用它取代「输入行右侧的旧文件面板」(含下载/删除);`reveal`、`terminal`、
|
||||
> `pick-dir` 仍只在 `AGENT_LOCAL_PICK=1` 下挂载(它们开的是跑 core 那台机器的窗口)。
|
||||
|
||||
### 新增 `local/`
|
||||
|
||||
| 文件 | 作用 |
|
||||
|---|---|
|
||||
| `start.sh` | 主入口:探测 → 首次生成配置 → 装依赖 → 起 core + MCP → 守护重启。**后台化**:拉起真正的启动器就返回 |
|
||||
| `stop.sh` | 停止启动器(按 `supervisor.pid` → core 的父进程 → 占端口的进程,三级兜底),幂等 |
|
||||
| `config.example.yml` | **仅作参考,不被读取**;实际配置由 `start.sh` 生成到 `config.local.yml` |
|
||||
| `preview-gateway.js` | 本地 office 预览网关(对位 executor 的 `:3100`,见 §4.15) |
|
||||
| `README.md` | 给使用者的说明(含安全边界、已知限制) |
|
||||
|
||||
`.gitignore` 增加 `local/.runtime/`、`local/config.local.yml`。
|
||||
|
||||
> 曾经有一个 `start.command`(macOS 双击入口),已删除:Finder 里双击 `.command` 常被系统当文本
|
||||
> 预览打开、不执行,而且它补的 PATH 探测和 `start.sh` 重复。现在唯一入口就是 `./local/start.sh`。
|
||||
|
||||
### 3.1 真机验证阶段补的修改
|
||||
|
||||
首次在 mac 上跑,暴露了下面这些;都不是设计变更,是实现跟设计对不上或漏了边界:
|
||||
|
||||
| 文件 | 改动 | 为的什么 |
|
||||
|---|---|---|
|
||||
| `local/start.sh` | 新增启动即弹出的**状态页**(`local/.runtime/status.html`,每秒自刷新) | 启动时终端看不到进度;失败页既没有应用名也没有日志,用户无从判断 |
|
||||
| `local/start.sh` | 依赖检测从「node_modules 在不在」改成**逐包实测 + `.agent-installed` 时间戳** | `npm install` 中途失败会留下半成品目录(目录在、包不全),原逻辑会永远跳过安装,core 起来就 require 失败 |
|
||||
| `local/start.sh` | `npm install` 输出 `tee` 到 `local/.runtime/npm-install.log`,并嵌进状态页 | 失败时只有终端能看到,滚过去就没了 |
|
||||
| `local/start.sh` | MCP 默认端口 3101~3104 → **8091~8094**;新增「PORT 撞 MCP 端口就拒绝启动」检查 | 跟 core 的 8090 连号,同时堵掉「换端口时不小心占用 MCP 端口」→ 子进程 bind 失败、静默降级 |
|
||||
| `local/start.sh` | 已有配置里的 MCP 端口与本次启动不一致时**告警** | 配置永不覆盖,改了默认值/用了 `MCP_*_PORT` 时,旧配置会让 core 静默发现不到工具 |
|
||||
| `local/start.sh` | 生成的 YAML 里路径**加引号** | 用户选的目录带空格/`:`/`#` 时会被 YAML 解析坏 |
|
||||
| `local/start.sh` | 没 ffmpeg 时**不再启动** `mcp_asr`(原实现无条件启动,与 4.3 的设计说明不符) | 否则模型拿到一个必然失败的 `transcribe_audio` 工具;同时少一个 `0.0.0.0` 监听 |
|
||||
| `local/start.sh` | 默认**后台化**(`AGENT_LOCAL_DETACH=1`),拉起启动器后 1 秒返回;新增 `local/stop.sh` | 用户不想让一个终端窗口永远挂着;Finder 里关窗口很容易误杀服务,后台 + 显式 `stop.sh` 更可控 |
|
||||
| `local/start.sh` | 没 node 时在入口就拦下(生成配置之前),并在终端打出安装方式 | 原来先进「选工作目录」、写好配置才报「后台进程立刻退出了」,用户白选一次,而且日志里只有两行启动横幅,看不出原因 |
|
||||
| `local/start.sh` | 同一轮只开一个状态页标签(`UI_OPENED`) | `ui_init` 已经开过一次,失败时 `ui_fail` 又开一个,同一个页面两个标签 |
|
||||
| `local/start.sh` | 「已在运行」改看 `supervisor.pid`(pid 存活且命令行是本脚本),health 只做兜底 | 只看 health 时 core 还没起来的几秒内连跑两次,会拉起两个启动器抢同一端口(实测:互相 `EADDRINUSE` 重启,`stop.sh` 只能停一个) |
|
||||
| `local/start.sh` | 首次安装**不自动跳转**,停在状态页给「打开应用」按钮;后续启动才 2 秒自动跳 | 首次装完先让用户看完「怎么配模型」再进去,别一上来就甩进空界面 |
|
||||
| `app/server/tools/executor.js` | 新增 `dispPath()`:会话目录外用绝对路径回显 | 宽根模式下写 `/tmp/x` 会回 `../../../../tmp/x`,模型容易当会话内路径二次拼接 |
|
||||
| `app/package-lock.json` | `resolved` 从腾讯云**内网镜像**改为公共 registry | 原 lockfile 把 tarball 钉在 `mirrors.tencentyun.com`(只有腾讯云 VPC 内能解析),外部机器 `npm install` 必失败,且换 `NPM_REGISTRY` 也无效 |
|
||||
|
||||
## 4. 关键设计决定(含「为什么」,别推翻)
|
||||
|
||||
### 4.1 开关用环境变量,不进 `config.yml`
|
||||
|
||||
`EXECUTOR_URL` / `ASR_URL` 已经是「部署接线走 env」的先例,本地模式属于同一类(部署形态),
|
||||
不是平台配置。好处是 `app/` 只需改 2 个文件,不必动 `config.js` 的 `DEFAULTS` 和
|
||||
`config.example.yml`(改配置项必须两处同步,是仓库的硬规则)。
|
||||
|
||||
### 4.2 配置**首次生成后永不覆盖**
|
||||
|
||||
`config.local.yml` 里既有启动器生成的字段(`workspace_root` / `skills_root`),也有用户在网页里
|
||||
配的东西(`platforms`、API Key、MCP headers)。每次启动重写会直接冲掉后者。
|
||||
|
||||
推论:**能力变化不能靠改配置实现**,只能靠 env / 起不起子进程 / 首次复制(见 4.3、4.4)。
|
||||
|
||||
### 4.3 ffmpeg 是运行时能力,与配置解耦
|
||||
|
||||
`routes/asr.js` 直接读 `process.env.ASR_URL`,`/api/asr/status` 在 `ASR_URL` 为空时返回
|
||||
`enabled:false`,前端 `voice.js` 据此**自动隐藏麦克风**。所以:
|
||||
|
||||
- 有 ffmpeg → 启动器起 `mcp_asr` + 注入 `ASR_URL`
|
||||
- 没 ffmpeg → 不起、不注入 → 麦克风自动消失
|
||||
|
||||
装完 ffmpeg 后**重跑脚本**即生效,配置文件一个字不用改。
|
||||
|
||||
### 4.4 技能是工作目录里的副本,不再软链仓库并随 python3 有无切换
|
||||
|
||||
用户选的工作目录被拆成三个兄弟目录:
|
||||
|
||||
```
|
||||
<工作目录>/tasks/ 会话工作区(AI 的文件根)
|
||||
<工作目录>/data/ SQLite、prompt dump
|
||||
<工作目录>/skills/ 技能 + deps/
|
||||
```
|
||||
|
||||
`skills_root` 写死 `<工作目录>/skills`(首次生成后不覆盖)。首次启动时把仓库 `skills/` 里的
|
||||
**内置技能逐个复制**过去,之后每次启动**只补缺、不覆盖**:
|
||||
|
||||
- 只复制目录,`deps` 不复制(仓库那份是服务器构建期产物,平台/版本都不该跟着走)
|
||||
- 目标已存在就跳过——用户改过的、AI 自己新建的技能都靠这条保住
|
||||
- 要拿仓库里的新版:删掉对应子目录再跑一次脚本
|
||||
|
||||
这样三个东西同时在位:仓库永远干净(`git status` 无未跟踪用户数据);用户数据一目录备份、
|
||||
一目录卸载;AI 真能“自己长技能”(新增目录即被发现,`skill list` 实时可见)。
|
||||
|
||||
早期版本把 `.runtime/skills` 软链到仓库,导致技能只能写回版本库(与仓库更新抢地盘)。
|
||||
更早还按 python3 有无切到空目录,想“别让模型看到跑不了的工具”——但技能不一定是 Python 的
|
||||
(`office` 只要 Node + 二进制),一刀切会把它们一并藏掉;而且 `skills.js` 的 `runEntry` 对
|
||||
`spawn` 的 `error` 有处理,缺解释器时模型拿到的是「技能入口启动失败:spawn python3 ENOENT」,
|
||||
干净可读,自己装完继续跑即可。
|
||||
|
||||
**没有改 `skills.js` 一行代码。**
|
||||
|
||||
### 4.5 启动器必须是守护进程
|
||||
|
||||
`routes/system.js` 的重启实现是「校验配置 → `process.exit(0)` → 等 Docker restart 策略拉起」,
|
||||
注释里写明「非 docker 部署不会自动重启」。本地没有 Docker,如果启动器只是前台 `node`,
|
||||
用户配完模型点一次「重启」,服务就再也回不来。
|
||||
|
||||
所以主循环是:起 core → 等健康 → `wait` → 非用户中断就 1 秒后重启;连续异常退出 5 次才停
|
||||
(防配置写坏导致无限刷屏)。`exit 0` 视为用户主动重启。
|
||||
|
||||
### 4.6 四个 MCP 必须分端口
|
||||
|
||||
容器里它们是四个独立容器、都监听 3000;本地同机必须错开(默认 **8091~8094**,紧跟 core 的 8090)。
|
||||
另外**它们的启动参数不统一**,这是个坑:
|
||||
|
||||
| 服务 | 启动方式 | 说明 |
|
||||
|---|---|---|
|
||||
| `web_search` | `node server.js --http --host --port` | 默认 host 已经是 `127.0.0.1` |
|
||||
| `image_task` | `node src/mcp-server.js --http --host --port` | 默认 `0.0.0.0` |
|
||||
| `video_task` | `node src/mcp-server.js --http --host --port` | 默认 `0.0.0.0` |
|
||||
| `mcp_asr` | **只认 `PORT` 环境变量** | 不解析 argv,且 `listen` 没带 host(= `0.0.0.0`) |
|
||||
|
||||
所以 `start.sh` 拆成 `start_mcp_flags` / `start_mcp_env` 两个函数,别合并。
|
||||
|
||||
### 4.7 `/tmp` 语义为什么分叉
|
||||
|
||||
服务器端:executor 在 session 模式下执行 `mount --bind <会话>/.tmp /tmp`,容器内 `/tmp` 的物理
|
||||
落点就是宿主 `<会话>/.tmp`。core 的文件工具必须去同一处找,否则 AI 用 terminal 写 `/tmp/x` 后
|
||||
`read_file /tmp/x` 读不到。所以那份「重定向」是**必需的**,不是 bug。
|
||||
|
||||
本地端:`toolTerminal` 是真 `spawn('/bin/sh')`,`/tmp` 就是本机 `/tmp`。此时再重定向就会造成
|
||||
「terminal 写真实 /tmp、file 工具读会话 .tmp」的错位——这正是 `AGENT_FILE_SCOPE=workspace`
|
||||
要关掉重定向的原因。
|
||||
|
||||
### 4.8 `skills_root` 的默认值
|
||||
|
||||
`skills.skills_root` 留空时默认取 `workspace_root` 的**同级** `skills` 目录。新的目录布局正好也是
|
||||
`tasks/` 与 `skills/` 同级,所以留空也能算对;但生成的配置仍然显式写死它——一个字段就能看出
|
||||
技能到底在哪,不依赖目录推导。
|
||||
|
||||
### 4.9 状态页:静态文件 + `meta refresh`,不起 HTTP 服务
|
||||
|
||||
启动时终端窗口不一定在前台,失败时也可能已经滚过去。所以启动就打开
|
||||
`local/.runtime/status.html`,并让它能自己更新:
|
||||
|
||||
- 脚本把状态写进 `local/.runtime/ui/` 下的几个小文件(`title` / `steps` / `busy` / `logpath` /
|
||||
`error` / `redirect`),`ui_render` 把它们拼成整页;页面用 `<meta http-equiv="refresh" content="1">`
|
||||
每秒重读一次。不需要常驻服务,所以「连 node 都没装」的环境也能打开。
|
||||
- 长步骤(`npm install`、等 core 健康检查)另起一个**心跳子进程**每秒重绘,页面上就能看到
|
||||
已经过了多少秒 + 当前日志的尾巴(npm 输出、core 启动报错)。
|
||||
- 状态全部落文件而不是留 shell 变量:心跳子进程拿到的是 fork 时的快照,用变量会越刷越旧。
|
||||
- 成功时:**首次安装**(配置是本次刚生成的)页面停在「已启动」,只给一个「打开应用」按钮,
|
||||
用户自己点(先看完下面的首次使用提示);**后续启动**写入 `redirect`,2 秒后自动进应用
|
||||
(同一个标签页,不多开窗)。
|
||||
- 失败时页面保留错误说明和日志尾部,并把完整日志路径写在页面上。
|
||||
- 默认只在 macOS 自动弹出(`AGENT_LOCAL_UI=auto`),Linux 服务器上要显式 `AGENT_LOCAL_UI=1`;
|
||||
无论弹不弹,页面都会生成。
|
||||
- 渲染先写临时文件再 `mv`:浏览器随时可能在刷新,不能让它读到半截 HTML;临时名用 `mktemp`
|
||||
而不是 `$$`——`$$` 在子 shell 里仍是主 shell 的 PID,心跳与主流程同时渲染会撞车。
|
||||
|
||||
### 4.10 依赖检测为什么不能只看 `node_modules` 目录
|
||||
|
||||
`npm install` 失败(断网、源不对)会留下一堆**空目录**:`app/node_modules` 在、`express` 目录
|
||||
也在,但里面没东西。原逻辑「目录存在且不比 `package.json` 旧」会判定为已安装,以后每次启动
|
||||
都跳过安装,core 起来立刻 `require` 失败——用户看到的是「装依赖那步过了,但服务起不来」。
|
||||
|
||||
现在的判定:
|
||||
|
||||
1. 逐个直接依赖检查 `node_modules/<dep>/package.json` 是否存在(比 `require.resolve` 可靠:
|
||||
`@modelcontextprotocol/sdk` 这类纯 ESM 包的 `exports.require` 指向的文件根本不存在,
|
||||
`require.resolve` 会误判成「没装」);
|
||||
2. 装成功后 `touch node_modules/.agent-installed`,只有 `package.json` 比它新才重装
|
||||
(npm 在「已经是最新」时不会更新 `node_modules` 的 mtime,只比目录 mtime 会每启动都白跑一次)。
|
||||
|
||||
### 4.11 后台化 + 显式 `stop.sh`,以及「已在运行」怎么判
|
||||
|
||||
用户不想为了跑一个本地服务永久占着一个终端窗口(而且关窗口可能连带杀掉进程)。所以:
|
||||
|
||||
- `start.sh` 自己**只做入口**:首次配置生成(要 tty 弹窗)→ `nohup` 拉起真正的启动器 → 1 秒后
|
||||
打印地址/状态页/停止命令并 `exit 0`。`AGENT_LOCAL_DETACHED=1` 是子进程标记,防无限重入。
|
||||
- 停止统一走 `local/stop.sh`。它按「`supervisor.pid` → core 的父进程 → 占端口的进程」三级兜底:
|
||||
只杀 core 会被守护循环重新拉起,所以必须能认出**启动器**。命令行是相对路径(`sh ./local/start.sh`),
|
||||
`pgrep -f` 匹配不到绝对路径,所以第一选择是 pid 文件。
|
||||
- 前台模式保留:`AGENT_LOCAL_DETACH=0 ./local/start.sh`(看实时日志、`Ctrl-C` 停)。
|
||||
|
||||
「已在运行」的判定不能只看 `/api/health`:core 起来要几秒(先起 MCP,首次还要装依赖),
|
||||
这期间再跟一次 `start.sh` 就会拉起第二个启动器,两个 core 抢同一个端口——一个被守护循环
|
||||
反复 `EADDRINUSE` 重启,而 `stop.sh` 只认 pid 文件里那一个,等于停不干净(已实测复现)。
|
||||
改成先看 `supervisor.pid`(子进程一启动就写,秒级就绪;`kill -0` + 命令行含 `start.sh` 防 pid 被回收),
|
||||
health 只作为「端口上有服务但不是本启动器拉起的」兜底提示。
|
||||
|
||||
### 4.12 依赖安装:源探测 + 换源重试 + 本地缓存(只在 `local/` 里做)
|
||||
|
||||
首装联网是逃不掉的,但「哪个源能用、卡住了怎么办」不该让用户想。启动器的策略:
|
||||
|
||||
1. **已装齐 → 不联网**(逐包检查 + `.agent-installed` 时间戳,见 4.10);
|
||||
2. **缓存命中 → 解压**:装成功后把 `node_modules` 打成
|
||||
`<平台>-<架构>-abi<ABI>-<依赖哈希>.tgz` 放 `~/.cache/agent-local/`;原生模块与 ABI 绑定,
|
||||
所以文件名必须含 ABI(`process.versions.modules`)。换 clone / 删 `node_modules` 都走这里,
|
||||
秒级且零网络;只留最近 3 份。
|
||||
3. **缓存未命中 → 选源安装**:并行探 `npmmirror` 与官方源(各 3 秒超时),取最快的;
|
||||
结果缓存一天。**只用命令行参数传源,绝不写 `~/.npmrc`**。
|
||||
4. **失败换源**:仅当用的是公共源(npmmirror / 官方)时换下一个重试,换源成功就记住;
|
||||
用户显式指定或公司私有源不兜底(乱兜底可能装错东西)。重试前先删半成品 `node_modules`。
|
||||
5. **看门狗**:npm 10 + Node 22 在断网时既不报错也不退出(已知的
|
||||
`Exit handler never called`,实测卡死超过 2 分钟),所以每次 `npm install` 都带超时,
|
||||
超时就 `SIGKILL` 整棵树再换源。
|
||||
6. **报错翻译**:把 npm 原文归成「网络没通 / 缺编译工具链(`xcode-select --install`)/
|
||||
没有写权限 / 源没响应」,状态页只显示这一句,原文仍完整落在 `npm-install.log`。
|
||||
|
||||
两个容易踩的实现细节(都踩过):
|
||||
|
||||
- `kill_tree` 不能把参数先赋给变量再递归:POSIX sh 没有局部变量,递归会覆盖它,回到外层
|
||||
kill 的是子进程而不是原本那个。
|
||||
- 看门狗只用 `SIGKILL`:先 `TERM` 会先干掉外壳让 npm 变成孤儿(`PPID=1`),`kill -0` 判不到,
|
||||
再想硬杀就找不到它了。
|
||||
|
||||
### 4.13 Python 包:不预装,交给模型按提示词装进 `skills/deps`
|
||||
|
||||
服务器上技能依赖由 `agent-executor-init` 一次性装进 `skills/deps`(compose 再把它放进
|
||||
`PYTHONPATH`)。本地没有这套东西,`start.sh` 也不去跑 pip——安装时机、镜像源、半成品清理
|
||||
是另一整套逻辑,收益不抵成本。做法改成「缺了再装」:
|
||||
|
||||
- `start.sh` 起 core 时注入 `PYTHONPATH=<工作目录>/skills/deps` 与
|
||||
`AGENT_SKILLS_DEPS=<工作目录>/skills/deps`(后者只为把路径交给模型)。
|
||||
`terminal` 与技能子进程都继承 core 的 env,所以装进去的东西**下次运行就能 import**,不用重启。
|
||||
- `templates/env-local.txt` 把原来的「永远不要自己装任何东西」改成「缺模块就装进
|
||||
`$AGENT_SKILLS_DEPS` 再重试」——**只给路径,不给命令**,怎么装由模型自己决定。
|
||||
技能失败时 stdout+stderr 是合并回给模型的,它能看到 `ModuleNotFoundError` 自己判断。
|
||||
- 为什么给一个目录而不是让模型自己选:那个目录已经在 `PYTHONPATH` 里,装进去下次运行就能
|
||||
import;而不指定位置的话,它很可能装到别处(或去改系统 Python)。pip 对 `--target` 的
|
||||
PEP 668 拦截明确豁免(`pip/_internal/commands/install.py`),所以这条路在 Homebrew 那种
|
||||
externally-managed 解释器上也走得通——但这话不写进提示词,交给模型自己判断。
|
||||
- 缺 `python3` 本体时也放给模型自己处理:本地形态是「用户自己的机器 + 用户自己的 agent」,
|
||||
目标是把事做成,而不是把它当生产环境保护。提示词只告诉它**装到哪**(Python 包进
|
||||
`$AGENT_SKILLS_DEPS`),不写条件也不写禁令——要不要先知会用户,交给模型按场合自己判断。
|
||||
- 技能自己的 `requirements.txt` 一律**不写版本号**:服务端 init 用
|
||||
`pip install --no-index --dry-run` 探测,pin 到与镜像不同的版本会让探测失败 → 真的往
|
||||
`skills/deps` 装一份旧的,而 `PYTHONPATH` 优先于系统 site-packages,等于反向遮蔽镜像包。
|
||||
|
||||
需要系统库的包(`weasyprint` → pango/cairo)pip 装不了,仍需用户 `brew install`;这类不在
|
||||
自动修复范围内,模型只报结论。
|
||||
|
||||
### 4.14 技能自洽:本机环境写在技能目录的 `AGENTS.md`
|
||||
|
||||
`install.sh` / `requirements.txt` 是服务器工件(镜像构建与 `agent-executor-init` 读它们),本机不跑、
|
||||
不改。启动器也不认识任何具体技能:不注入 PATH、不预装、不做特判。新增技能不需要动 `local/`。
|
||||
|
||||
本机缺东西时只有一条入口:技能自己目录下的 `AGENTS.md`。它是**排错清单**,只写「现象 → 命令」
|
||||
(报什么错、敲什么),不写背景、不提服务器。起点是 `env-local` 提示词的一句话:技能失败就读
|
||||
`"$(dirname "$AGENT_SKILLS_DEPS")/<技能>/AGENTS.md"`。装完不需要重启,旧进程不影响。
|
||||
|
||||
分两层,各管各的:**技能目录的 `AGENTS.md` 只写该技能特有的**(缺哪个包、缺什么系统库);
|
||||
**网络换源与长任务这类通用规则不进技能文档**,直接写在 `env-local.txt` 提示词里——
|
||||
它们必须常驻上下文,靠「出错时去翻文件」是拉不动的(尤其长任务:AI 决定跑 `brew install` 的
|
||||
那一刻没有任何报错信号触发它去查文档)。
|
||||
|
||||
代价明写:`office` 的命令入口在本地不在 PATH 上,按次 `PATH="$SK/scripts:$PATH" office ...` 即可
|
||||
(这是它 `AGENTS.md` 的第一条)。
|
||||
|
||||
报错指向各自文档,不在 core 里做全局特征匹配(那种正则既脆又不可移植):
|
||||
|
||||
| 位置 | 报错附带 |
|
||||
|---|---|
|
||||
| `office` 封装层 ENOENT | 本技能 `AGENTS.md` 绝对路径 |
|
||||
| `x2pdf` 缺包 / 无渲染后端 | 同上 |
|
||||
| `image-process` 缺中文字体 | 同上(并提示传 `font`) |
|
||||
| 网络类 / 长任务 | 不进技能文档:写在 `env-local.txt`,常驻上下文 |
|
||||
|
||||
唯一保留的环境相关代码是 `x2pdf` 的 `find_soffice()`:`brew install --cask libreoffice` 后
|
||||
`soffice` 不在 PATH(在 app bundle 内),不探这几个默认位置,“装 LibreOffice 即可”就是假的。
|
||||
另保留了 WeasyPrint 不可用时回落 LibreOffice,让本地只需一个后端而不是 pango + WeasyPrint 两套链。
|
||||
|
||||
没做的是预览:预览卡片要 executor 的 `:3100` 网关,本地没有——这一项后来补了,见 §4.15。
|
||||
|
||||
### 4.15 office 文档预览:本地自建一个薄网关
|
||||
|
||||
服务器上「点开 docx」是 core → 反代 `/preview` → executor 的 `:3100` 网关 → 网关按需 spawn
|
||||
`officecli watch`。本地没有 executor,链路断在中间。补法不是改 core,而是在 `local/` 里放一个
|
||||
零依赖网关,用 `PREVIEW_PROXIES` 把它登记进 core 的反代注册表(`app/` 一行没改)。
|
||||
|
||||
**不复用 `executor/preview.js`**:那套 `unshare --mount --pid` + `nsenter` + `mount --bind` 是为
|
||||
「让沙箱内的命令和 watch 看见同一个世界」造的(vendor 靠 `TMPDIR` 下的句柄文件 + 回环 TCP 相互
|
||||
发现)。本地没有沙箱,命令和 watch 本来就同机同盘,那些系统调用不但用不上,有些平台根本没有。
|
||||
于是本地网关只剩数据面:
|
||||
|
||||
- `/preview/<会话id>/<相对路径>` → 解析真实文件 → 确保有 watch → 剥前缀转发
|
||||
- `/`、`/events`(SSE)与 `/api/*` → 按 `Referer` 认领槽位转发(`/` 尤其关键:vendor 把根绝对
|
||||
`/` 当「自身最新 HTML」比对,回 404 它就 `location.reload()`,用户看到的是白屏后重载)
|
||||
- 4 个槽位,LRU 挤占 + 闲置回收;watch 端口从 26315 起按代轮转,跳过已被占用的
|
||||
- 就绪 = 真发一次 `GET /`(首帧渲染在那次请求里完成);裸 TCP 连上只说明 Kestrel bind 好了
|
||||
- HEAD 探针等槽位就绪再回 200(有上限):冷启动渲染不落到 iframe 的导航请求上
|
||||
- 导航请求绝不为启动/自愈阻塞:未就绪或外部改动 → 立刻中转页 + 后台热槽;缺尾斜杠补 301
|
||||
- 外部写盘靠 mtime 指纹 + 2s 轮询 `POST /api/switch` 触发重读;`__pv-touch` 是编辑命令的事后一脚
|
||||
- 槽位带活性校验:watch 自己退了就丢掉重起,转发出错也立即摘槽(GET/HEAD 再自愈重试一次)
|
||||
- 缺 `officecli` 时给「安装说明页」,而不是无限转圈:服务器那份二进制是构建期必装的,
|
||||
`preview.js` 从没为「没装」设计;本地全新 clone 一定没有,这是常态不是异常
|
||||
|
||||
于是本地 `office` 的体验与服务器一致:`create`/`open` 后聊天里出预览卡片,点开即右侧预览,
|
||||
`get-pos` 能读到选区。技能侧因此不需要任何本地分支(`skills/office` 与服务器同源)。
|
||||
|
||||
平台差异都收在两处:进程回收(POSIX 杀进程组 / Windows `taskkill /T`)、二进制解析(`.exe`、
|
||||
POSIX 补 `chmod +x`、`officecli-*` 资产名也认)。其余只用 Node 内置能力。
|
||||
|
||||
已知:watch 没有 `--host` 参数,只能绑 `0.0.0.0`(与 `mcp_asr` 同类);网关与 core 只在回环上。
|
||||
|
||||
## 5. 验证结果(macOS 12.7.6 / x86_64 / Node 22.21 / python3 3.10 / 本机无 ffmpeg)
|
||||
|
||||
静态检查:`sh -n local/start.sh`、`sh -n local/stop.sh`、`node --check` 均通过。
|
||||
|
||||
| 项 | 结果 |
|
||||
|---|---|
|
||||
| 首次启动:生成配置 → 装依赖(app 134 包,image_task / video_task 各 127 包)→ 起 MCP + core → 打开状态页(停在「已启动」,等点击) | 通过 |
|
||||
| 配置内容:`workspace_root` = `<选定目录>/tasks`、`data_root` = `<选定目录>/data`、`skills_root` = `<选定目录>/skills`(内置技能已复制)、`platforms: []`、MCP 端口 8091~8094 | 通过 |
|
||||
| 绑定地址:`lsof` 只有 `127.0.0.1:8090` | 通过 |
|
||||
| 设置页「重启」→ 守护拉起:PID 变化,2 秒内 `/api/health` 恢复 | 通过 |
|
||||
| 文件工具限定在 `<工作目录>/tasks/` 下:放进 `tasks/` 的 `probe.txt` 可读,`<工作目录>/data/` 报路径越界 | 待复测 |
|
||||
| 越界保护:`read_file ~/.ssh/config`、`terminal cd /etc` 均报「路径越界」 | 通过 |
|
||||
| `/tmp` 一致性:`write_file /tmp/x` → `terminal cat /tmp/x` 与 `read_file /tmp/x` 内容一致 | 通过 |
|
||||
| 无 ffmpeg:`/api/asr/status` = `enabled:false`(麦克风隐藏),asr 子进程不启动,8094 不监听 | 通过 |
|
||||
| 有 python3:Python 技能可执行;桩掉 python3 后技能清单不变(`/api/skills` 照常返回),执行 `run.py` 类技能报「技能入口启动失败:spawn python3 ENOENT」,`office` 这类非 Python 技能不受影响 | 待复测 |
|
||||
| 四个 MCP 在具备条件时均能发现工具(`[mcp] web_search / image_task / video_task / asr: 发现 1 个工具`) | 通过 |
|
||||
| 前台模式 `Ctrl-C` 与 `TERM`:8090 与 8091~8094 全部释放,无残留进程 | 通过 |
|
||||
| 二次启动:沿用配置、跳过依赖安装(时间戳生效) | 通过 |
|
||||
| 后台模式:`start.sh` 1 秒返回、启动器 PPID=1、`supervisor.pid` 是子进程 pid | 通过 |
|
||||
| `stop.sh`:命中 pid 文件分支;pid 文件丢失时按 core 父进程/端口也能停;未运行时幂等返回 | 通过 |
|
||||
| 重复执行 `start.sh`:打印「已在运行(启动器 pid N)」+ 停止命令,exit 0,不起第二个进程 | 通过 |
|
||||
| 启动器被 `kill -9` 后的恢复:残留 pid 文件被清理,端口仍被占时明确提示先 `stop.sh` | 通过 |
|
||||
| 依赖源自动探测:删依赖后启动,自动选中 `registry.npmmirror.com`(本机 npm 全局源也是它),状态页显示「依赖源」 | 通过 |
|
||||
| 依赖缓存:装成功后生成 `~/.cache/agent-local/deps-...tgz`;删掉 `node_modules` 重启,日志为「使用本地依赖缓存」、`npm-install.log` 为空(零网络) | 通过 |
|
||||
| 换源自愈:把缓存里的源改成不可达地址 → 看门狗超时 → 自动换到 npmmirror 装完,缓存里的源被改回可用值 | 通过 |
|
||||
| 失败翻译:源不可用 + 冷 npm 缓存 → 状态页标题「依赖安装失败」、提示「源没有响应…(已自动换源重试)」,无 npm 残留进程 | 通过 |
|
||||
| 前台模式 `AGENT_LOCAL_DETACH=0`:阻塞运行,`TERM` 后端口全部释放 | 通过 |
|
||||
| 无 node(PATH 里剥掉 node/npm):入口直接拦下,**不** 先让选目录、不生成配置;终端打出安装方式;状态页列出自检项(X Node.js / X npm) | 通过 |
|
||||
| 失败时只开一个状态页标签(不再两个) | 通过 |
|
||||
| 状态页:启动即弹出、每秒刷新、显示步骤/计时/日志尾巴;失败时保留错误与日志 | 通过 |
|
||||
| 预览网关(直接打网关,临时 tasks 根):HEAD 探针 200、GET 200、自动起 watch @26315 | 通过 |
|
||||
| 预览数据面:`/events` 是真 SSE、`/api/selection` 204、`/api/send` 200;无 `Referer` 404 | 通过 |
|
||||
| 缺 `officecli`:给安装说明页,HEAD 仍 200(面板不闪死链) | 通过 |
|
||||
| 网关退出:watch 端口释放,无残留进程 | 通过 |
|
||||
| 冷 HEAD 等首帧(3.3s)回 200;随后热导航 10ms 拿到页面 | 通过 |
|
||||
| vendor 的根绝对 `/`(带 Referer):200 且与页面 HTML 逐字节相同(不再触发 `location.reload()` 白屏) | 通过 |
|
||||
| 冷启动导航:2.7ms 回中转页(不等启动),4 秒后刷新即真页面 | 通过 |
|
||||
| 缺尾斜杠导航:301 到带斜杠的页面 | 通过 |
|
||||
| `__pv-touch`:命中活槽位 → `{"touched":true}`;外部 `touch` 文件 → 2s 轮询 POST `/api/switch` → SSE 收到 `"action":"full"` | 通过 |
|
||||
| 槽位自愈:`kill -9` 掉 watch 后再请求,自动在下一代端口重起(26315 → 26316),页面照常返回 | 通过 |
|
||||
| 经 core 的 `/preview` 端到端(含手选工作目录、`work_dir` 在 `tasks/` 外的会话) | 待复验 |
|
||||
| `osascript` 真实选目录弹窗 | 未验证(用桩跑的「没选→回落 `~/AgentWork`」分支) |
|
||||
| 真浏览器打开(`open`) | 未验证(用桩记录了被打开的 URL) |
|
||||
| 装 ffmpeg 之后:`ASR_URL` 注入、asr 子进程与麦克风一起出现 | 未验证(本机未装 ffmpeg) |
|
||||
|
||||
验证过程中发现并修掉的问题见 3.1(依赖检测、lockfile 内网源、`asr` 无条件启动、端口冲突、
|
||||
状态页日志缺失、全角字符紧贴变量名导致的 `unbound variable`)。
|
||||
|
||||
## 6. 还没覆盖的三项(需要人工交互或外部环境)
|
||||
|
||||
其余清单已在 mac 上跑完(结果见第 5 节)。剩下这三项要在真实场景里补:
|
||||
|
||||
1. **真实选目录弹窗**:删掉 `local/config.local.yml` 后跑 `./local/start.sh`,确认弹出的是 macOS 原生
|
||||
选目录窗、选完的路径写进 `workspace_root`(带空格的目录名要顺手验一下,配置里已加引号)。
|
||||
2. **真浏览器打开**:跑 `./local/start.sh`(或前台模式),确认(a)状态页在启动过程中每秒刷新;
|
||||
(b)首次安装停在页面上等你点「打开应用」;(c)后续启动 2 秒自动进应用。
|
||||
3. **装 ffmpeg 之后**:`brew install ffmpeg` → 重跑脚本,预期:状态页显示 `ffmpeg` 为 OK、
|
||||
终端打「语音:可用」、8094 开始监听、`/api/asr/status` 变成需要填上游(不再是「未设置 ASR_URL」)。
|
||||
|
||||
手工复验用的命令:
|
||||
|
||||
```bash
|
||||
./local/start.sh # 后台启动(1 秒返回)
|
||||
./local/stop.sh # 停止(幂等)
|
||||
./local/start.sh # 已在运行时只打印地址与停止方式
|
||||
lsof -nP -iTCP:8090 -sTCP:LISTEN # 应只有 127.0.0.1
|
||||
lsof -nP -iTCP:8091-8094 -sTCP:LISTEN # 3 或 4 个 MCP(没 ffmpeg 时没有 8094)
|
||||
curl -s http://127.0.0.1:8090/api/asr/status
|
||||
curl -s -X POST http://127.0.0.1:8090/api/system/restart # 应由守护拉起
|
||||
tail -f local/.runtime/core.log # 以及 npm-install.log / mcp-*.log
|
||||
```
|
||||
|
||||
## 7. 已知限制(都不打算在本次解决)
|
||||
|
||||
| 限制 | 说明 |
|
||||
|---|---|
|
||||
| **无沙箱** | AI 的 `terminal` 就是本机 shell,能读 `~/.ssh` 等一切。这是「给它一个目录就放开手脚」的代价;README 已提示「专用目录 + `git init`」 |
|
||||
| 没 ffmpeg 时 asr 会报「工具发现失败」 | 此时 `mcp_asr` 不启动(它转码依赖 ffmpeg),但配置里的 asr 条目仍在(配置不覆盖),所以 core 启动会 warn 一次并重试,属预期 |
|
||||
| `mcp_asr` 监听 `0.0.0.0` | 它只认 `PORT` 环境变量、`listen` 不带 host(已启动时才是问题)。不存密钥(上游参数随请求带入),暴露面有限;要收紧需给 `mcp/asr` 加 `--host` 支持 |
|
||||
| Windows 不支持 | `spawn('/bin/sh')`、`process.kill(-pid)`、模型写的 bash 语法都是 POSIX 语义 |
|
||||
| 链接只在本机可达 | 本地没有公网前缀:`mint_public_link` / 页面访问地址都签成 `http://127.0.0.1:<PORT>/...`,只能在这台机器上打开(这正是本地形态的预期)。要真正对外暴露才需在设置页填 `public_link.base_url` |
|
||||
| 技能依赖 | 本地不预装:缺包时模型会把包装进 `<工作目录>/skills/deps`(`$AGENT_SKILLS_DEPS`,已在该进程 `PYTHONPATH` 里,装完下次运行即生效);连 `python3` 都没有时也由它自己装。怎么装由模型自己决定。需要系统库的包(`weasyprint`→pango/cairo)pip 装不了,仍需手工 `brew install`。服务器上由 `agent-executor-init` 处理 |
|
||||
| `office` 二进制 | 不入库、也不预装:首次用到时报 `binary missing` 并给出该技能 `AGENTS.md` 的绝对路径,模型按它自己下载(`releases/latest`,~34MB,GitHub 慢就用 gh-proxy)。不需要 root、不需重启。officecli 会自更新到 latest,版本比服务器 pin 的新属正常 |
|
||||
| `office` 预览 | 本地网关按需起 `officecli watch`,体验与服务器一致;但 watch 没有 `--host`,只能绑 `0.0.0.0`,且预览进程闲置 6h 回收(槽位 4 个) |
|
||||
| 首个 `npm install` 要联网 | 支持 `NPM_REGISTRY` 覆盖源;`app/package-lock.json` 的 `resolved` 已改指向公共 registry(原来钉在内网镜像,外部机器必失败) |
|
||||
|
||||
## 8. 回滚
|
||||
|
||||
本地模式的所有开关默认关闭,服务器行为不变。真要整体撤掉:
|
||||
|
||||
```bash
|
||||
git revert <本次提交>
|
||||
rm -rf local/ # 或保留脚本、只是不用
|
||||
```
|
||||
|
||||
`v2.5.0` 是这批改动之前的基线,可随时对照。
|
||||
|
||||
## 9. 记录:测试残留(都不入库)
|
||||
|
||||
跑过启动器之后本机会多出:`local/.runtime/`(日志、状态页)、`local/config.local.yml`、
|
||||
你选的工作目录(`data/` `skills/` `tasks/`)、`app/node_modules/`、`mcp/image_task|video_task/node_modules/`。
|
||||
仓库里只有前两项,且都在 gitignore 内;用户数据全在工作目录里,删掉它等于彻底重置。
|
||||
|
||||
## 10. 新建会话手选工作目录(本地端)
|
||||
|
||||
默认每个会话落在 `workspace_root/<会话id>`(形如 `task-YYYYMMDD-NNN`)。本地端希望「给它一个
|
||||
目录就放开手脚」,所以新建会话时可以手选一个真实目录,这个会话的 AI 一切操作都在那儿。
|
||||
|
||||
**后端只动 `taskDirOf` 一处**(`engine.js`):
|
||||
|
||||
```js
|
||||
taskDirOf(sessionId) = sessions.work_dir || path.join(workspace_root, sessionId)
|
||||
```
|
||||
|
||||
全仓库的会话路径(文件 API、上传、`terminal` 的 cwd、`resolveInTask` 基准、data-page、
|
||||
`@会话` 只读)都经由它,所以改这一处即全线生效,不必逐个路由改。
|
||||
|
||||
- 选择只存前端(`pendingWorkDir`),建档时随 `POST /api/sessions` 提交一次;不选 = 空串 = 老行为。
|
||||
- **不建 `task-*` 子目录**,直接以所选目录为工作目录(隐藏产物 `.tmp`/`.imgcache`/`.app`/`data.db` 落在这里)。
|
||||
- 允许多个会话选同一目录;**删会话绝不删该目录**(`deleteSession` 只在 `work_dir` 为空时才 `rmSync`)。
|
||||
- `fsRoot` 优先返回 `ctx.workDir`;`@<会话>` 也按目标会话的 `work_dir` 解析(`resolvePastPath`)。
|
||||
- 目录选择器:`routes/local.js` 用 `osascript`(mac)/ `zenity`/`kdialog`(Linux)弹原生窗口,
|
||||
**仅 `AGENT_LOCAL_PICK=1` 时挂载**(`server.js`),服务器形态 `/api/local/*` 一律 404,前端整条入口隐藏。
|
||||
必须 `execFile` 异步:同步会阻塞事件循环、卡住所有 SSE。
|
||||
- 只接受已存在的目录(`normalizeWorkDir` 校验真实路径),并拒绝根目录 `/` 与平台数据目录。
|
||||
- 服务器形态:前端从不传 `work_dir`,`work_dir` 列恒为空,行为与旧版完全一致。
|
||||
+190
@@ -0,0 +1,190 @@
|
||||
# 本地端(local 模式)
|
||||
|
||||
把同一个 `agent-core` 直接跑在本机(macOS / Linux),不装 Docker、不起 executor。
|
||||
|
||||
它和服务器版是**同一份代码**,差别只在三件事,全部由 `local/start.sh` 注入:
|
||||
|
||||
| 差异 | 服务器 | 本地 |
|
||||
|---|---|---|
|
||||
| 命令在哪跑 | `agent-executor` 容器(mount/pid namespace 隔离) | 直接在本机 `spawn`(无沙箱) |
|
||||
| 文件工具的根 | 会话目录 `tasks/<会话id>/` | 你选的工作目录下的 `tasks/` |
|
||||
| 监听地址 | `0.0.0.0`(靠宿主机端口映射对外) | `127.0.0.1`(只有本机能访问) |
|
||||
|
||||
后两项分别由环境变量 `AGENT_FILE_SCOPE=workspace` 和 `HOST=127.0.0.1` 控制,容器部署不设置,
|
||||
行为与以前完全一致。
|
||||
|
||||
## 快速开始
|
||||
|
||||
```bash
|
||||
cd agent
|
||||
./local/start.sh # 后台启动,命令 1 秒就返回,可以关掉终端窗口
|
||||
./local/stop.sh # 停止
|
||||
```
|
||||
|
||||
首次运行会:
|
||||
|
||||
1. 自检环境(Node 20+ 必需;ffmpeg / python3 可选),并打开一个**启动状态页**
|
||||
2. 弹窗让你选一个**工作目录**,在里面建 `data/`、`skills/`、`tasks/` 三个子目录
|
||||
3. 把仓库 `skills/` 里的内置技能复制到 `<工作目录>/skills/`
|
||||
4. 生成 `local/config.local.yml`
|
||||
5. 装一次 Node 依赖(`app/` 与带依赖的 MCP,需要联网)
|
||||
6. 起 core + MCP 子进程(没 ffmpeg 时 asr 不启动)
|
||||
7. 停在那儿守护:core 退出就自动拉起
|
||||
|
||||
工作目录是你的:数据库、会话、技能都在里面,仓库里不存任何运行数据。
|
||||
|
||||
浏览器里首次使用:**左下角「用户区」→ 设置 → 模型池**,添加平台和 API Key,然后点「重启」。
|
||||
|
||||
新建会话时,欢迎页「随时开始吧」下方可以**手选一个工作目录**:选了之后这个会话的 AI 一切操作
|
||||
都在那个目录里(不再建 `task-*` 子目录);不选就沿用默认(`<工作目录>/tasks/<会话id>`)。
|
||||
删会话不会删你选的目录。
|
||||
|
||||
没有 Node 20+ 时不会让你白选目录:脚本在入口就停下,终端打出安装方式,自检结果(哪项缺、怎么装)写到状态页。
|
||||
|
||||
> 「重启」能用是因为启动器在守护。`routes/system.js` 的重启实现是 `process.exit(0)`,
|
||||
> 原本靠 Docker 的 restart 策略拉起;本地没有 Docker,没有守护的话点一次服务就回不来了。
|
||||
|
||||
启动器在后台常驻,所以:
|
||||
|
||||
- 关掉终端窗口**不会**停服务;要停就 `./local/stop.sh`
|
||||
- 重复跑 `./local/start.sh` 是安全的:检测到已在运行就只打印地址和停止方式
|
||||
- 想在终端里看实时日志、用 `Ctrl-C` 停:`AGENT_LOCAL_DETACH=0 ./local/start.sh`
|
||||
|
||||
## 启动状态页
|
||||
|
||||
启动时会在浏览器打开 `local/.runtime/status.html`(macOS 默认自动弹,Linux 要 `AGENT_LOCAL_UI=1`):
|
||||
|
||||
- 启动过程中每秒自动刷新,依次列出环境自检、工作目录、依赖安装、MCP、core 就绪
|
||||
- 长步骤(装依赖、等 core 起来)会显示已用时间,并把 npm / core 日志的尾巴实时刷出来
|
||||
- **首次安装**(配置刚生成)不自动跳转:就停在这一页,点「打开应用」自己进去
|
||||
- **后续启动**:就绪后 2 秒自动进应用(同一个标签页)
|
||||
- **失败时就在页面上给出原因和日志**,不用回头翻终端
|
||||
|
||||
这个页面是纯静态文件(不用起服务),所以“node 都没装”的时候也能打开。重跑脚本会重新生成;
|
||||
即使没自动弹出,文件也一直在那个路径。
|
||||
|
||||
## 可选能力
|
||||
|
||||
| 能力 | 需要 | 没有时的表现 |
|
||||
|---|---|---|
|
||||
| 语音输入 | `ffmpeg` + 设置页给 `asr` 填上游(`X-ASR-Base-Url` / `X-ASR-Model`) | 麦克风入口自动隐藏(`/api/asr/status` 返回 `enabled:false`),`mcp_asr` 子进程也不启动 |
|
||||
| 技能 | `python3`(仅 Python 类技能需要) | 技能清单照常显示;调 `run.py` 类技能报「入口启动失败」,`office` 这类非 Python 技能不受影响 |
|
||||
| Office 文档(docx/xlsx/pptx) | 首次用到时下载一次 officecli 二进制(约 34MB) | `office` 报 `binary missing` 并给出该技能 `AGENTS.md` 的路径,按它下载即可(不需 root、不需重启);预览面板里直接显示同一份安装说明 |
|
||||
| 网页搜索 | 无 | 装了 Node 就有(内置免费后端) |
|
||||
| 图片 / 视频生成 | 设置页给对应 MCP 填上游 key | 调用时报明确的缺参错误 |
|
||||
|
||||
装完 `ffmpeg` 之后**重跑一次 `./local/start.sh`** 即可生效。`python3` 稍特殊:技能清单本来就在,
|
||||
只要新装的解释器落在 core 启动时 `PATH` 已包含的目录里(如 brew 的 `/opt/homebrew/bin`)就无需重启;
|
||||
换了目录就重跑脚本。这三项都不写进配置,靠「起不起子进程 / 注入什么环境变量」切换。
|
||||
|
||||
## 配置放哪
|
||||
|
||||
你选的工作目录下:
|
||||
|
||||
| 路径 | 内容 |
|
||||
|---|---|
|
||||
| `<工作目录>/data/` | SQLite(`.agent.db`)、启动时的 prompt dump |
|
||||
| `<工作目录>/tasks/` | 会话工作区,一个会话一个 `task-YYYYMMDD-NNN/` |
|
||||
| `<工作目录>/skills/` | 技能;内置技能首次启动时复制过来,以后只补缺不覆盖。依赖装在 `skills/deps/` |
|
||||
|
||||
仓库里只有:
|
||||
|
||||
- 生成的配置:`local/config.local.yml`(**首次生成,之后永不覆盖**,避免冲掉你在网页里配的模型与密钥)
|
||||
- 运行期产物:`local/.runtime/`(`status.html` 状态页、`core.log`、`npm-install.log`、`mcp-*.log`、`preview.log` + `watch-<端口>.log`)
|
||||
|
||||
想彻底重来:删掉 `local/config.local.yml` 再启动(工作目录里的数据不会动,重选一个目录就换一套)。
|
||||
技能要跟着仓库更新:删掉 `<工作目录>/skills/<技能名>` 再启动,脚本会把新版补回来(你自建的技能不受影响)。
|
||||
|
||||
## 常用环境变量
|
||||
|
||||
| 变量 | 默认 | 说明 |
|
||||
|---|---|---|
|
||||
| `PORT` | `8090` | core 端口(别撞下面的 MCP 端口) |
|
||||
| `NPM_REGISTRY` | 空 | 手动指定 npm 源(默认自动探测;指定后不再自动换源) |
|
||||
| `MCP_WEB_PORT` / `MCP_IMAGE_PORT` / `MCP_VIDEO_PORT` / `MCP_ASR_PORT` | 8091~8094 | 四个 MCP 的端口(同机跑必须各占一个;改这里还要同步改配置里的 url) |
|
||||
| `PREVIEW_PORT` | `3100` | office 文档预览网关的端口(被占时自动往后找);watch 自己的端口从 26315 起 |
|
||||
| `AGENT_LOCAL_UI` | `auto` | 是否自动打开状态页:`auto` = 仅 macOS,`1` 强制,`0` 关闭(页面无论如何都会生成) |
|
||||
| `AGENT_LOCAL_DETACH` | `1` | `1` = 后台启动后立即返回(用 `stop.sh` 停);`0` = 前台阻塞(看实时日志、`Ctrl-C` 停) |
|
||||
| `AGENT_LOCAL_CACHE` | `~/.cache/agent-local` | 依赖缓存的存放位置(多个 clone 共享) |
|
||||
| `AGENT_LOCAL_NPM_TIMEOUT` | `240` | 单次 `npm install` 的超时秒数,超过就换源重试 |
|
||||
|
||||
## 依赖安装与网络(国内环境)
|
||||
|
||||
首次启动要装一次 Node 依赖,启动器会自己处理环境问题,不需要你操心:
|
||||
|
||||
- **自动选源**:并行探 `registry.npmmirror.com` 与官方源,用最快的那个(国内基本会选 npmmirror)。
|
||||
结果缓存一天;不写你本机的 `~/.npmrc`,也不改全局配置。
|
||||
- **失败自动换源重试**:一个源不行就换下一个;换源成功会记住它。
|
||||
- **卡住有看门狗**:npm 在断网时可能既不报错也不退出,超过 `AGENT_LOCAL_NPM_TIMEOUT` 就结束它并换源。
|
||||
- **装完存缓存**:打成一张 tarball 放到 `~/.cache/agent-local/`。之后重启、删掉 `node_modules`、
|
||||
再 clone 一份,都是解压恢复(秒级、零网络)。
|
||||
- **失败说人话**:状态页会直接告诉你「网络没通 / 缺编译工具链(`xcode-select --install`)/ 没有写权限」,
|
||||
不需要读 npm 日志。
|
||||
|
||||
要清缓存就删那个目录:`rm -rf ~/.cache/agent-local`(下次启动会重新装一次)。
|
||||
|
||||
## 更新
|
||||
|
||||
```bash
|
||||
git pull
|
||||
./local/stop.sh && ./local/start.sh # package.json 变了会自动重装依赖
|
||||
```
|
||||
|
||||
`app/server` 是直接跑源码,前端也是免构建的,所以改完代码重启(或在网页点「重启」)即生效。
|
||||
|
||||
## 安全边界(务必知情)
|
||||
|
||||
本地模式**没有沙箱**:AI 的 `terminal` 就是本机 shell,能读写你账号有权限的任何文件,
|
||||
包括 `~/.ssh`、浏览器数据、其它项目。这不是配置疏漏,而是「给它一个目录就放开手脚」的代价。
|
||||
|
||||
两条低成本保险:
|
||||
|
||||
1. 工作目录选一个**专用**目录,别直接选 `$HOME` 或整个代码仓库根
|
||||
2. 那个目录先 `git init` 一下,改坏了能回滚
|
||||
|
||||
另外,`core` 只监听 `127.0.0.1`,同一局域网的人访问不到。
|
||||
|
||||
## 已知限制
|
||||
|
||||
- **没 ffmpeg 时 core 日志会有一条 `asr 工具发现失败`**:此时 `mcp_asr` 不启动(它转码要靠
|
||||
ffmpeg),但配置里的 asr 条目仍保留(配置不被覆盖)。重试几次后放弃,不影响其它功能。
|
||||
- **`mcp_asr` 启动后监听 `0.0.0.0`**:它只认 `PORT` 环境变量,没有 `--host` 参数
|
||||
(另外三个服务都传了 `--host 127.0.0.1`)。它不存任何密钥(上游参数随请求带入),
|
||||
暴露面有限,但严格起见可以给 `mcp/asr` 补一个 `--host` 支持。
|
||||
- **Windows 暂不支持**:本机执行走 `spawn('/bin/sh')` 与 `process.kill(-pid)`,都是 POSIX 语义。
|
||||
- **链接只在本机可达**:没有公网前缀时,`mint_public_link` 与页面访问地址都会签成
|
||||
`http://127.0.0.1:<PORT>/...`,在这台机器上点得开,发给别人打不开。要对外暴露再填
|
||||
`public_link.base_url`(设置页)。本地监听回环地址,模型厂商也拉不到,所以读图回传改走内联
|
||||
base64(`AGENT_IMAGE_INLINE=1`,启动器已注入)。
|
||||
- **`office` 预览依赖 `officecli`**:网关按需起 `officecli watch`(最多 4 个,闲置 6 小时回收)。
|
||||
没装二进制时预览面板会直接显示安装说明,不会无限转圈。watch 只能监听 `0.0.0.0`(它没有
|
||||
`--host` 参数),同机其它用户理论上能访问那几个端口。
|
||||
- **技能依赖不预装**:本地没有 `agent-executor-init`,技能自带的 `requirements.txt` 不会在启动时
|
||||
自动安装。缺包时会报 `ModuleNotFoundError`,模型会把缺的包装进 `<工作目录>/skills/deps`
|
||||
(`AGENT_SKILLS_DEPS` 指向它,且已在该进程的 `PYTHONPATH` 里,装完下次运行即生效)。
|
||||
连 `python3` 都没有时技能清单依旧完整,模型会自己把它装上再继续。
|
||||
需要系统库的包(如 `weasyprint` 依赖 pango/cairo)pip 装不了,得自己 `brew install`。
|
||||
- **首个 `npm install` 要联网**:启动器会自动选源、换源重试、并把装好的依赖缓存到
|
||||
`~/.cache/agent-local/`;之后重启 / 换 clone 都是本地解压,不需要网络。真要手动指定源:
|
||||
`NPM_REGISTRY=https://registry.npmmirror.com ./local/start.sh`。中途失败留下的半成品
|
||||
`node_modules` 不用手删(换源重试前会自动清)。
|
||||
|
||||
## 排查
|
||||
|
||||
```bash
|
||||
open local/.runtime/status.html # 启动状态页:步骤、失败原因、日志尾巴
|
||||
tail -f local/.runtime/core.log # core 日志(含 prompt dump 路径、MCP 发现结果)
|
||||
tail -f local/.runtime/npm-install.log # 装依赖的输出
|
||||
tail -f local/.runtime/mcp-asr.log # 单个 MCP 的日志
|
||||
tail -f local/.runtime/preview.log # office 预览网关(watch 启动失败的原因也在这)
|
||||
```
|
||||
|
||||
启动失败时状态页会自己弹出(带错误说明和日志尾部);它是个静态页,所以改完环境要自己重跑脚本
|
||||
(它不会自动重试)。
|
||||
|
||||
进程表 / 端口对不上时:
|
||||
|
||||
```bash
|
||||
lsof -nP -iTCP:8090-8094 -sTCP:LISTEN # core + 四个 MCP 的监听情况
|
||||
lsof -nP -iTCP:3100 -sTCP:LISTEN # 预览网关(没用 office 时不存在)
|
||||
```
|
||||
@@ -0,0 +1,49 @@
|
||||
# 本机 local 模式的配置参考。
|
||||
#
|
||||
# ⚠️ 这个文件不会被读取,只是给人看的样板:真正的配置由 local/start.sh 首次运行时
|
||||
# 生成到 local/config.local.yml(含你选的工作目录与分配好的端口)。
|
||||
# 想看自己机器上实际生成成什么样,启动一次后直接打开 local/config.local.yml。
|
||||
#
|
||||
# 字段含义与服务器版完全一致(见 app/config.example.yml);下面只列 local 模式实际用到的那部分。
|
||||
|
||||
port: 8090
|
||||
|
||||
# 你选的工作目录下的三个子目录:tasks(会话工作区)、data(数据库等)、skills(技能)。
|
||||
|
||||
# AI 的工作根:文件工具的根就是它,AI 看不到同级的 data/ 与 skills/。
|
||||
workspace_root: /Users/you/AgentWork/tasks
|
||||
|
||||
# SQLite(.agent.db)与启动 prompt dump。
|
||||
data_root: /Users/you/AgentWork/data
|
||||
|
||||
skills:
|
||||
# 技能根。首次启动时从仓库 skills/ 复制内置技能过来,之后只补缺不覆盖;
|
||||
# pip 装的依赖落在同级的 deps/。
|
||||
skills_root: /Users/you/AgentWork/skills
|
||||
|
||||
# 留空:启动后到设置页添加平台与 API Key,再点「重启」(启动器负责把进程拉起来)。
|
||||
platforms: []
|
||||
|
||||
log_level: info
|
||||
|
||||
mcp_servers:
|
||||
# 四个同栈 MCP 由启动器在本机拉起,端口与 start.sh 里的默认值对应(8091~8094,
|
||||
# 紧跟在 core 的 8090 后面;改 PORT 时别撞上这四个)。
|
||||
# web_search 不需要任何密钥(内置免费后端);其余三个的上游参数在设置页卡片里填,
|
||||
# 会写进对应条目的 headers。
|
||||
- name: web_search
|
||||
url: "http://127.0.0.1:8091/"
|
||||
- name: image_task
|
||||
url: "http://127.0.0.1:8092/mcp"
|
||||
mode: skill
|
||||
- name: video_task
|
||||
url: "http://127.0.0.1:8093/mcp"
|
||||
mode: skill
|
||||
- name: asr
|
||||
url: "http://127.0.0.1:8094/mcp"
|
||||
mode: skill
|
||||
# 例:填了这两项才算启用语音(缺 X-ASR-Base-Url 时 /api/asr/status 返回 enabled:false,麦克风自动隐藏)
|
||||
# headers:
|
||||
# Authorization: Bearer <key>
|
||||
# X-ASR-Base-Url: "https://<host>/v1"
|
||||
# X-ASR-Model: "whisper-1"
|
||||
@@ -0,0 +1,718 @@
|
||||
#!/usr/bin/env node
|
||||
// local/preview-gateway.js —— 本地 office 文档预览网关(对位服务器上 executor 的 :3100)。
|
||||
//
|
||||
// 为什么要有它:服务器上「点开 docx」这条链是 core → 反代 /preview → executor 预览网关 →
|
||||
// 网关自己按需 spawn `officecli watch`。本地没有 executor,那条链路会断,面板里是个空 iframe。
|
||||
// 这里用零依赖 Node 复刻 executor/preview.js 的**数据面**,但不复刻它的隔离层:
|
||||
// 服务器给 watch 造 pid/mount ns 牢笼、bind 会话 .tmp 到 /tmp,是为了让**沙箱里的命令**
|
||||
// 和 watch 看见同一个世界(vendor 用 TMPDIR 下的 .port 文件 + TCP 回环发现彼此)。
|
||||
// 本地既没有沙箱,命令和 watch 本来就在同一个文件系统、同一个临时目录里,
|
||||
// 那些 unshare/nsenter 不但用不上,有些平台上根本不存在。于是这里只剩数据面:
|
||||
//
|
||||
// 1. /preview/<会话id>/<相对路径>/ → 解析成真实文件 → 确保它有 watch → 转发
|
||||
// 2. 页内数据面(/events、/api/*、以及 vendor 拿去比对自身的 /)→ 按 Referer 认领槽位转发
|
||||
// 3. 槽位:最多 N 个并发 watch,挤占最久未用的,闲置回收
|
||||
// 4. 缺 officecli 时给人能看懂的一页,而不是无限转圈(服务器那份二进制是构建期必装的,
|
||||
// 所以 executor 那份没为「没装」设计过;本地全新 clone 一定没有,这是常态不是异常)
|
||||
//
|
||||
// 与服务器实现逐条对齐的几处(都踩过,别简化掉):
|
||||
// - 探活 = 真发一次 `GET /`(首帧渲染就在这次请求里完成),裸 TCP 连上只说明 Kestrel bind 好了
|
||||
// - HEAD 探针等槽位就绪(有上限)再回 200:否则冷启动的首次渲染全砸在 iframe 的导航请求上
|
||||
// - 导航请求绝不为启动/自愈阻塞首字节:未就绪 → 立刻回中转页 + 后台热槽
|
||||
// - vendor 页把 `/` 当作「自身最新 HTML」来比对,回 404 它就 location.reload() —— 用户看到白屏
|
||||
// - 外部写盘(不走 officecli 的)靠 mtime 指纹 + 2s 轮询 POST /api/switch 触发重读
|
||||
//
|
||||
// 平台:只用 Node 内置能力,进程回收/二进制名/可执行位都按平台分支,不假设 POSIX。
|
||||
// 监听回环(默认 127.0.0.1:3100),唯一入口仍是 core 的 /preview 反代(登录门禁在那边)。
|
||||
'use strict';
|
||||
const fs = require('node:fs');
|
||||
const fsp = require('node:fs').promises;
|
||||
const http = require('node:http');
|
||||
const net = require('node:net');
|
||||
const path = require('node:path');
|
||||
const { spawn } = require('node:child_process');
|
||||
|
||||
const WIN = process.platform === 'win32';
|
||||
|
||||
const HOST = process.env.OFFICE_PREVIEW_HOST || '127.0.0.1';
|
||||
const PORT = Number(process.env.OFFICE_PREVIEW_PORT || 3100);
|
||||
const PREFIX = (process.env.OFFICE_PREVIEW_PREFIX || '/preview').replace(/\/+$/, '');
|
||||
const SLOTS = Math.max(1, Number(process.env.OFFICE_SLOTS || 4));
|
||||
const WATCH_BASE = Number(process.env.OFFICE_WATCH_BASE || 26315);
|
||||
const WATCH_SPAN = Math.max(SLOTS, Number(process.env.OFFICE_WATCH_SPAN || 64));
|
||||
const IDLE_MS = Number(process.env.OFFICE_IDLE_MS || 6 * 3600 * 1000);
|
||||
const RESPOND_TIMEOUT_MS = Number(process.env.OFFICE_RESPOND_TIMEOUT_MS || 15000); // 数据请求等首响包
|
||||
const NAV_TIMEOUT_MS = Number(process.env.OFFICE_NAV_TIMEOUT_MS || 5000); // 导航请求更短:失败转中转页
|
||||
const COOLDOWN_MS = Number(process.env.OFFICE_COOLDOWN_MS || 8000); // 启动失败后短期不再重试
|
||||
const HEAD_WAIT_MS = Number(process.env.OFFICE_HEAD_WAIT_MS || 15000); // 探针等首帧的上限
|
||||
const NAV_TIMEOUT_RETRIES = 3; // 连续导航超时几次才判死
|
||||
|
||||
// 会话真实目录:默认 <tasks 根>/<会话id>;手选过工作目录的会话要问 core 拿 work_dir(本地免鉴权)。
|
||||
const TASKS_ROOT = path.resolve(process.env.AGENT_TASKS_ROOT || process.cwd());
|
||||
const SKILLS_ROOT = path.resolve(process.env.AGENT_SKILLS_ROOT || path.join(TASKS_ROOT, '..', 'skills'));
|
||||
const REPO_ROOT = path.resolve(process.env.AGENT_REPO_ROOT || path.join(__dirname, '..'));
|
||||
const RUNTIME = path.resolve(process.env.AGENT_RUNTIME || path.join(__dirname, '.runtime'));
|
||||
const CORE_URL = process.env.AGENT_CORE_URL || '';
|
||||
const EXTS = new Set(['.docx', '.xlsx', '.pptx']);
|
||||
const SID_RE = /^task-[0-9A-Za-z_-]+$/;
|
||||
|
||||
const slots = new Map(); // 文件绝对路径 → { file, port, watch, pageDec, ready, readyP, lastUsed, conns, ... }
|
||||
const starting = new Map(); // 文件绝对路径 → Promise:同文件并发请求合并成一次 spawn
|
||||
const cooldown = new Map(); // 文件绝对路径 → 冷却截止时间戳
|
||||
const dirCache = new Map(); // 会话id → 真实目录(只缓存命中,避免会话晚建时永久失效)
|
||||
let watchGen = 0; // watch 端口按代轮转:残留孤儿占着旧口也不会被新槽撞上
|
||||
|
||||
const log = (msg) => process.stdout.write(new Date().toISOString() + ' ' + msg + '\n');
|
||||
|
||||
// ---------- 小工具 ----------
|
||||
function escapeHtml(s) {
|
||||
return String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
}
|
||||
|
||||
// 二进制解析:每次 spawn 时才做——AI 按技能 AGENTS.md 装好之后,用户点一下刷新就该能用,不该要求重启网关。
|
||||
// 名字不一定是 officecli:官方资产叫 officecli-<平台>-<架构>[.exe],AI 很可能原样下载,所以标准名之后
|
||||
// 再认同目录里任何 officecli* 可执行文件。可执行位只在 POSIX 上有意义,且 curl 下来的资产常常是 0644,
|
||||
// 这里顺手补一下(不能要求调用者先 chmod)。
|
||||
function executable(p) {
|
||||
if (WIN) {
|
||||
try { return fs.statSync(p).isFile(); } catch (_) { return false; }
|
||||
}
|
||||
try { fs.accessSync(p, fs.constants.X_OK); return true; } catch (_) {}
|
||||
try { fs.chmodSync(p, 0o755); fs.accessSync(p, fs.constants.X_OK); return true; } catch (_) { return false; }
|
||||
}
|
||||
|
||||
function binDirs() {
|
||||
return [path.join(SKILLS_ROOT, 'office', 'bin'), path.join(REPO_ROOT, 'skills', 'office', 'bin')];
|
||||
}
|
||||
|
||||
function resolveBin() {
|
||||
const env = String(process.env.OFFICECLI_BIN || '').trim();
|
||||
if (env && executable(env)) return env;
|
||||
const std = WIN ? ['officecli.exe', 'officecli'] : ['officecli'];
|
||||
const dirs = binDirs();
|
||||
for (const d of dirs) {
|
||||
for (const n of std) {
|
||||
const p = path.join(d, n);
|
||||
if (executable(p)) return p;
|
||||
}
|
||||
}
|
||||
for (const d of dirs) {
|
||||
let list = [];
|
||||
try { list = fs.readdirSync(d).sort(); } catch (_) { continue; }
|
||||
for (const n of list) {
|
||||
if (!/^officecli/i.test(n)) continue;
|
||||
if (WIN ? !/\.exe$/i.test(n) : /\.(?:log|txt|md|zip|tar|gz|sha\d*)$/i.test(n)) continue;
|
||||
const p = path.join(d, n);
|
||||
if (executable(p)) return p;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// 端口能不能连上(判「有没有人在听」)。注意它**不能**当就绪判定:Kestrel bind 完成就能连,
|
||||
// 首帧还没渲染;就绪一律用 portUp(真发一次 GET /)。
|
||||
function portListening(port) {
|
||||
return new Promise((resolve) => {
|
||||
const s = net.connect({ host: '127.0.0.1', port, timeout: 800 });
|
||||
let done = false;
|
||||
const fin = (v) => { if (done) return; done = true; try { s.destroy(); } catch (_) {} resolve(v); };
|
||||
s.once('connect', () => fin(true));
|
||||
s.once('timeout', () => fin(false)); // 回环上不回 SYN 几乎不存在,按空闲处理
|
||||
s.once('error', () => fin(false));
|
||||
});
|
||||
}
|
||||
|
||||
// 就绪探活:真发一次 `GET /`(首帧渲染在这次请求里完成,后续浏览器请求走 vendor 的页内缓存)。
|
||||
// 任何状态码都算活着;拒连/超时继续重试,预算 40 次 x 250ms。
|
||||
function portUp(port, tries = 40) {
|
||||
return new Promise((resolve, reject) => {
|
||||
let n = 0;
|
||||
const probe = () => {
|
||||
const rq = http.get({ host: '127.0.0.1', port, path: '/', timeout: 2000 }, (up) => {
|
||||
up.resume();
|
||||
resolve();
|
||||
});
|
||||
const retry = () => {
|
||||
if (++n >= tries) return reject(new Error('watch 未在预期时间内就绪'));
|
||||
setTimeout(probe, 250);
|
||||
};
|
||||
rq.on('error', retry);
|
||||
rq.on('timeout', () => { try { rq.destroy(); } catch (_) {} retry(); });
|
||||
};
|
||||
probe();
|
||||
});
|
||||
}
|
||||
|
||||
// 端口代次轮转 + 领取前确认空闲:AI 手动起的 watch、以及被杀的旧 watch 残留,都占着固定口。
|
||||
async function allocPort() {
|
||||
for (let i = 0; i < WATCH_SPAN; i++) {
|
||||
const p = WATCH_BASE + (watchGen++ % WATCH_SPAN);
|
||||
let used = false;
|
||||
for (const s of slots.values()) if (s.port === p) { used = true; break; }
|
||||
if (used) continue;
|
||||
if (!(await portListening(p))) return p;
|
||||
}
|
||||
throw new Error('没有空闲的 watch 端口(' + WATCH_BASE + '~' + (WATCH_BASE + WATCH_SPAN - 1) + ')');
|
||||
}
|
||||
|
||||
// 回收 watch:POSIX 上它自成进程组(detached),按组杀才不会留下占端口的子进程;
|
||||
// Windows 没有进程组信号,用 taskkill /T 连子树一起收。
|
||||
function killTree(child) {
|
||||
if (!child || !child.pid) return;
|
||||
if (WIN) {
|
||||
try { spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore', windowsHide: true }); return; } catch (_) {}
|
||||
} else {
|
||||
try { process.kill(-child.pid, 'SIGKILL'); return; } catch (_) {}
|
||||
}
|
||||
try { child.kill('SIGKILL'); } catch (_) {}
|
||||
}
|
||||
|
||||
function killWatch(entry) {
|
||||
// 已退出的进程不再按 pid 杀:pid 可能已被系统回给别的进程组(POSIX 上是 -pid)
|
||||
if (entry.watch && entry.watch.exitCode === null && entry.watch.signalCode === null) killTree(entry.watch);
|
||||
}
|
||||
|
||||
function stopEntry(entry, why) {
|
||||
const key = entry.file;
|
||||
if (slots.get(key) === entry) slots.delete(key);
|
||||
killWatch(entry);
|
||||
if (why) log('回收槽位 ' + path.basename(key) + '(' + why + ')');
|
||||
}
|
||||
|
||||
// ---------- 页面 ----------
|
||||
function htmlPage(res, title, body, autoRefresh, code) {
|
||||
const html = '<!doctype html><html lang="zh-CN"><head><meta charset="utf-8">' +
|
||||
'<title>' + escapeHtml(title) + '</title>' +
|
||||
(autoRefresh ? '<meta http-equiv="refresh" content="' + autoRefresh + '">' : '') +
|
||||
'<style>body{font-family:-apple-system,system-ui,sans-serif;margin:0;padding:40px;line-height:1.7;color:#222}' +
|
||||
'h1{font-size:18px;margin:0 0 12px}code{background:#f2f2f2;padding:1px 5px;border-radius:3px;font-size:13px}' +
|
||||
'p{margin:8px 0;max-width:46em;color:#444}</style></head><body>' +
|
||||
'<h1>' + escapeHtml(title) + '</h1>' + body + '</body></html>';
|
||||
res.writeHead(code || 200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' });
|
||||
res.end(html);
|
||||
}
|
||||
|
||||
// 中转页:槽位在启动/刚死,先给浏览器一个纯 CSS 转圈 + 自动刷新,别白屏干等(与服务器同一张页)。
|
||||
function loading(res) {
|
||||
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' });
|
||||
res.end('<!doctype html><meta charset="utf-8"><meta http-equiv="refresh" content="2">' +
|
||||
'<title>正在准备预览</title><style>' +
|
||||
'html,body{height:100%;margin:0;font-family:system-ui,-apple-system,sans-serif;background:#fafafa;color:#666}' +
|
||||
'.w{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);text-align:center}' +
|
||||
'.s{width:36px;height:36px;margin:0 auto 14px;border:3px solid #ddd;border-top-color:#4a90d9;border-radius:50%;animation:r 1s linear infinite}' +
|
||||
'@keyframes r{to{transform:rotate(360deg)}}p{font-size:14px}' +
|
||||
'</style><div class="w"><div class="s"></div><p>正在准备预览,请稍候。</p></div>');
|
||||
}
|
||||
|
||||
function installPage(res) {
|
||||
const bin = path.join(SKILLS_ROOT, 'office', 'bin', WIN ? 'officecli.exe' : 'officecli');
|
||||
htmlPage(res, 'office 预览组件未安装',
|
||||
'<p>预览需要 <code>officecli</code> 二进制,这台机器上还没有。</p>' +
|
||||
'<p>它应该放在 <code>' + escapeHtml(bin) + '</code>。</p>' +
|
||||
'<p>让 AI 打开一次这个文档即可(说「用 office 打开这个文档」)——它会按技能目录里的 ' +
|
||||
'<code>AGENTS.md</code> 自己下载好;装完点下面的按钮刷新,不用重启服务。</p>' +
|
||||
'<p><button onclick="location.reload()">刷新</button></p>');
|
||||
}
|
||||
|
||||
function notFound(res) {
|
||||
// no-store:前端拿 HEAD 当探针,404 一旦被浏览器缓存,文件补上后还会继续显示「暂无文档」
|
||||
res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' })
|
||||
.end('无匹配预览(文档不存在、不在会话目录下,或不是 .docx/.xlsx/.pptx)');
|
||||
}
|
||||
|
||||
function fail502(res) {
|
||||
if (!res.headersSent) {
|
||||
res.writeHead(502, { 'content-type': 'text/plain; charset=utf-8' }).end('预览暂时不可用,请稍后重试');
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 会话目录与路径护栏 ----------
|
||||
function coreGet(pathname) {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!CORE_URL) return reject(new Error('未配置 AGENT_CORE_URL'));
|
||||
const u = new URL(CORE_URL);
|
||||
const req = http.request({ host: u.hostname, port: u.port, path: pathname, method: 'GET', timeout: 3000 }, (res) => {
|
||||
let body = '';
|
||||
res.setEncoding('utf8');
|
||||
res.on('data', (c) => { body += c; });
|
||||
res.on('end', () => {
|
||||
if (res.statusCode !== 200) return reject(new Error('core ' + res.statusCode));
|
||||
try { resolve(JSON.parse(body)); } catch (e) { reject(e); }
|
||||
});
|
||||
});
|
||||
req.on('error', reject);
|
||||
req.on('timeout', () => { req.destroy(new Error('core 超时')); });
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
async function sessionDir(sid) {
|
||||
if (dirCache.has(sid)) return dirCache.get(sid);
|
||||
const plain = path.join(TASKS_ROOT, sid);
|
||||
let dir = fs.existsSync(plain) ? plain : '';
|
||||
if (!dir) {
|
||||
// 手选工作目录的会话:只有 core 知道真实路径(sessions.work_dir)。
|
||||
// 接口回的是 { session, ... },limit=1 只为别把整段历史拉回来。
|
||||
try {
|
||||
const row = await coreGet('/api/sessions/' + encodeURIComponent(sid) + '?limit=1');
|
||||
const wd = String((row && row.session && row.session.work_dir) || '');
|
||||
if (wd && fs.existsSync(wd)) dir = wd;
|
||||
} catch (_) { /* core 没起来 / 会话不存在:下面按缺失处理 */ }
|
||||
}
|
||||
if (dir) dirCache.set(sid, dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
// /preview/<会话id>/<相对路径> → { sid, dir, abs, rel };越界(..、绝对路径)与非办公文档一律 null。
|
||||
async function guard(sid, rawRel) {
|
||||
if (!SID_RE.test(sid)) return null;
|
||||
const dir = await sessionDir(sid);
|
||||
if (!dir) return null;
|
||||
const rel = rawRel.replace(/^\/+/, '');
|
||||
const abs = path.resolve(dir, rel);
|
||||
if (abs !== dir && !abs.startsWith(dir + path.sep)) return null;
|
||||
if (!EXTS.has(path.extname(abs).toLowerCase())) return null;
|
||||
try { await fsp.access(abs); } catch (_) { return null; }
|
||||
return { sid, dir, abs, rel: path.relative(dir, abs).split(path.sep).join('/') };
|
||||
}
|
||||
|
||||
function pageOf(t) {
|
||||
return '/' + t.sid + '/' + t.rel; // 页面前缀(已解码):槽位按它寻址
|
||||
}
|
||||
|
||||
// 路由:rel = 已解码、剥掉 PREFIX 的请求路径(形如 /task-x/doc.docx/…);最长前缀优先。
|
||||
// exact = 命中的就是页面本身(此时缺尾斜杠要 301,否则页面内相对资源会解析错)。
|
||||
function matchPage(rel) {
|
||||
if (!rel) return null;
|
||||
const rr = rel.startsWith('/') ? rel : '/' + rel;
|
||||
const cut = rr.replace(/\/+$/, '');
|
||||
let best = null;
|
||||
for (const s of slots.values()) {
|
||||
if (cut === s.pageDec) return { entry: s, exact: true };
|
||||
if (cut.startsWith(s.pageDec + '/')) {
|
||||
if (!best || s.pageDec.length > best.entry.pageDec.length) best = { entry: s, exact: false };
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
// ---------- watch 生命周期 ----------
|
||||
async function spawnWatch(t) {
|
||||
const bin = resolveBin();
|
||||
if (!bin) {
|
||||
const e = new Error('缺少 officecli 二进制');
|
||||
e.code = 'MISSING_BIN';
|
||||
throw e;
|
||||
}
|
||||
// 槽满:优先踢「就绪且无活动连接」里最久未用的;正在启动的槽最后才动(踢掉它等于白费冷启动)
|
||||
if (slots.size >= SLOTS) {
|
||||
const list = [...slots.values()];
|
||||
const pick = (list.filter((s) => !s.conns && s.ready).length ? list.filter((s) => !s.conns && s.ready)
|
||||
: list.filter((s) => !s.conns).length ? list.filter((s) => !s.conns) : list)
|
||||
.sort((a, b) => a.lastUsed - b.lastUsed)[0];
|
||||
if (pick) stopEntry(pick, '槽满挤占');
|
||||
}
|
||||
const port = await allocPort();
|
||||
try { await fsp.mkdir(RUNTIME, { recursive: true }); } catch (_) {}
|
||||
const logPath = path.join(RUNTIME, 'watch-' + port + '.log');
|
||||
const fd = fs.openSync(logPath, 'a');
|
||||
const child = spawn(bin, ['watch', t.abs, '--port', String(port)], {
|
||||
cwd: t.dir,
|
||||
detached: !WIN, // POSIX:自成进程组便于整组回收;Windows 靠 taskkill /T
|
||||
windowsHide: true,
|
||||
stdio: ['ignore', fd, fd],
|
||||
env: Object.assign({}, process.env, {
|
||||
// 与技能封装层同一组开关:不变式模式跑 .NET、改动即落盘、关自动 resident
|
||||
DOTNET_SYSTEM_GLOBALIZATION_INVARIANT: '1',
|
||||
OFFICECLI_NO_AUTO_RESIDENT: '1',
|
||||
OFFICECLI_RESIDENT_FLUSH: 'each',
|
||||
}),
|
||||
});
|
||||
try { fs.closeSync(fd); } catch (_) {}
|
||||
|
||||
const entry = {
|
||||
file: t.abs, port, watch: child, pageDec: pageOf(t),
|
||||
lastUsed: Date.now(), conns: 0, ready: false, readyP: null, navTimeouts: 0,
|
||||
mtimeMs: 0, size: -1, logPath,
|
||||
};
|
||||
let exited = null;
|
||||
child.on('exit', (code, sig) => {
|
||||
exited = { code, sig };
|
||||
if (slots.get(entry.file) === entry) slots.delete(entry.file); // 死了就别留在册(否则一直转发到死端口)
|
||||
});
|
||||
child.on('error', (e) => { exited = { code: -1, sig: String((e && e.message) || e) }; });
|
||||
slots.set(entry.file, entry); // 同步占坑(未就绪):并发请求等 readyP,绝不盲转发
|
||||
|
||||
let markDead;
|
||||
const dead = new Promise((_, rej) => { markDead = rej; });
|
||||
const deadTimer = setInterval(() => { if (exited) markDead(new Error('watch 进程提前退出')); }, 100);
|
||||
deadTimer.unref();
|
||||
|
||||
entry.readyP = Promise.race([
|
||||
portUp(port).then(() => { entry.ready = true; log('起 watch ' + path.basename(t.abs) + ' @' + port); }),
|
||||
dead,
|
||||
]).catch((e) => {
|
||||
if (slots.get(entry.file) === entry) slots.delete(entry.file);
|
||||
killWatch(entry);
|
||||
throw e instanceof Error ? e : new Error('watch 启动失败:' + ((e && e.message) || e));
|
||||
}).finally(() => clearInterval(deadTimer));
|
||||
|
||||
try {
|
||||
await entry.readyP;
|
||||
} catch (e) {
|
||||
let tail = '';
|
||||
try { tail = fs.readFileSync(logPath, 'utf8').split('\n').slice(-3).join(' | ').trim(); } catch (_) {}
|
||||
const err = new Error(e.message + (tail ? ':' + tail : ''));
|
||||
err.logPath = logPath;
|
||||
throw err;
|
||||
}
|
||||
// mtime+size 作为本次渲染的指纹:导航侧对照,外部写盘后回收重渲染
|
||||
try { const st = await fsp.stat(t.abs); entry.mtimeMs = st.mtimeMs; entry.size = st.size; } catch (_) {}
|
||||
return entry;
|
||||
}
|
||||
|
||||
async function startWatch(t) {
|
||||
const have = slots.get(t.abs);
|
||||
if (have) { have.lastUsed = Date.now(); return have; }
|
||||
const cool = cooldown.get(t.abs);
|
||||
if (cool && Date.now() < cool) throw new Error('刚才启动失败,稍后再试');
|
||||
if (starting.has(t.abs)) return starting.get(t.abs);
|
||||
const p = spawnWatch(t).then(
|
||||
(entry) => { starting.delete(t.abs); cooldown.delete(t.abs); return entry; },
|
||||
(err) => {
|
||||
starting.delete(t.abs);
|
||||
cooldown.set(t.abs, Date.now() + COOLDOWN_MS);
|
||||
log('watch 启动失败 ' + t.abs + ':' + err.message);
|
||||
throw err;
|
||||
},
|
||||
);
|
||||
starting.set(t.abs, p);
|
||||
return p;
|
||||
}
|
||||
|
||||
// 未命中兜底:请求路径本身就是存在的会话文档 → 就地冷启动。不行 = null。
|
||||
async function revive(decRel) {
|
||||
const rr = (decRel || '').replace(/\/+$/, '');
|
||||
if (!rr) return null;
|
||||
const segs = rr.split('/').filter(Boolean);
|
||||
const sid = segs.shift() || '';
|
||||
const t = await guard(sid, segs.join('/'));
|
||||
if (!t) return null;
|
||||
try { await startWatch(t); return { entry: slots.get(t.abs), exact: false }; } catch (_) { return null; }
|
||||
}
|
||||
|
||||
// 数据请求用:拿到「就绪」的槽位,等正在启动的那次;启动刚失败就再补一次。
|
||||
async function waitReady(decRel) {
|
||||
for (let round = 0; round < 2; round++) {
|
||||
let m = matchPage(decRel);
|
||||
if (!m) m = await revive(decRel);
|
||||
if (!m || !m.entry) return null;
|
||||
if (m.entry.ready) return m;
|
||||
await m.entry.readyP.catch(() => {});
|
||||
if (m.entry.ready) return m;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// 探针预热:把槽位等到「就绪」(= 首帧渲染完成),复用时直接返回。任何失败/超时都静默。
|
||||
async function warmSlot(decRel, t) {
|
||||
let timer;
|
||||
try {
|
||||
await Promise.race([
|
||||
(async () => {
|
||||
const have = slots.get(t.abs);
|
||||
if (have && have.ready) return;
|
||||
const e = await startWatch(t);
|
||||
if (!e.ready) await e.readyP.catch(() => {});
|
||||
})(),
|
||||
new Promise((r) => { timer = setTimeout(r, HEAD_WAIT_MS); }),
|
||||
]);
|
||||
} catch (_) {} finally { clearTimeout(timer); }
|
||||
}
|
||||
|
||||
// 就地重读:POST watch /api/switch(同路径 = 强制从磁盘重载),watch 原生推 doc-switched,页面自刷。
|
||||
function notifySwitch(entry) {
|
||||
try {
|
||||
const q = http.request({ host: '127.0.0.1', port: entry.port, path: '/api/switch', method: 'POST', timeout: 8000,
|
||||
headers: { 'content-type': 'application/json' } }, (up) => { up.resume(); });
|
||||
q.on('error', () => {});
|
||||
q.on('timeout', () => { try { q.destroy(); } catch (_) {} });
|
||||
q.end(JSON.stringify({ file: entry.file }));
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
// ---------- 转发 ----------
|
||||
const PASS_HEADERS = new Set(['accept', 'accept-encoding', 'cache-control', 'pragma', 'content-type',
|
||||
'content-length', 'if-modified-since', 'if-none-match', 'last-event-id', 'referer', 'user-agent']);
|
||||
|
||||
// 单次转发:拒连/首响应超时 → reject(此时尚未向浏览器写出任何字节,可安全改道);
|
||||
// 已出字节的流内失败只能毁掉响应(SSE 长流的正常路径不受看门狗影响)。
|
||||
function tryForward(entry, req, res, innerPath, respondTimeoutMs) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const selfHost = '127.0.0.1:' + entry.port;
|
||||
const headers = {};
|
||||
for (const k of Object.keys(req.headers)) if (PASS_HEADERS.has(k)) headers[k] = req.headers[k];
|
||||
// watch 的同源校验只认回环:从别的名字(host 名解析到 127.0.0.1)打开 core 时会被 403
|
||||
if (req.headers.origin) headers.origin = 'http://' + selfHost;
|
||||
|
||||
const search = req.url.indexOf('?') >= 0 ? req.url.slice(req.url.indexOf('?')) : '';
|
||||
const inner = innerPath.startsWith('/') ? innerPath : '/' + innerPath;
|
||||
|
||||
entry.lastUsed = Date.now();
|
||||
entry.conns = (entry.conns || 0) + 1;
|
||||
let released = false;
|
||||
const release = () => { if (!released) { released = true; entry.conns = Math.max(0, entry.conns - 1); } };
|
||||
res.once('close', release);
|
||||
res.once('finish', release);
|
||||
|
||||
let started = false;
|
||||
let upRes = null;
|
||||
const upstream = http.request(
|
||||
{ host: '127.0.0.1', port: entry.port, path: encodeURI(inner) + search, method: req.method, headers },
|
||||
(up) => {
|
||||
started = true;
|
||||
upRes = up;
|
||||
clearTimeout(watchdog);
|
||||
const h = Object.assign({}, up.headers);
|
||||
delete h.connection; delete h['keep-alive'];
|
||||
const isSSE = String(h['content-type'] || '').includes('text/event-stream');
|
||||
if (isSSE) { h['cache-control'] = 'no-cache'; h['x-accel-buffering'] = 'no'; }
|
||||
res.writeHead(up.statusCode || 502, h);
|
||||
up.on('data', (d) => {
|
||||
entry.lastUsed = Date.now();
|
||||
// 抓到「真改文档」的原生推送(牢笼内 CLI 编辑会推 excel-patch/full 等):给轮询器一个吸收窗口。
|
||||
// 只认改文档的 action —— selection-update/mark-update 是 UI 态,把页内编辑的救场 switch 也吸掉就永不刷新了
|
||||
if (isSSE && /"action":"(?:full|excel-patch|word-patch|replace|add|remove)"/.test(String(d))) entry.lastNative = Date.now();
|
||||
});
|
||||
up.pipe(res);
|
||||
resolve();
|
||||
});
|
||||
const watchdog = setTimeout(() => {
|
||||
if (started) return;
|
||||
try { upstream.destroy(); } catch (_) {}
|
||||
release();
|
||||
if (!res.headersSent) reject(new Error('watch 响应超时'));
|
||||
}, respondTimeoutMs || RESPOND_TIMEOUT_MS);
|
||||
upstream.on('error', () => {
|
||||
clearTimeout(watchdog);
|
||||
release();
|
||||
if (!started && !res.headersSent) return reject(new Error('watch 不可达'));
|
||||
// 已开始回写后上游报错:留一拍再判(watch 会在响应其实已完整时断链,对 HEAD 必现)
|
||||
setTimeout(() => {
|
||||
if (res.writableEnded) return;
|
||||
try { res.destroy(); } catch (_) {}
|
||||
}, upRes && upRes.complete ? 0 : 120);
|
||||
});
|
||||
req.pipe(upstream);
|
||||
});
|
||||
}
|
||||
|
||||
// 转发自愈一次:失败 → 摘槽 → 同页原地复活 → 重试。GET/HEAD 才可重试(无请求体,重放无副作用)。
|
||||
async function forwardHealed(entry, req, res, innerPath) {
|
||||
try { await tryForward(entry, req, res, innerPath); return true; }
|
||||
catch (e) {
|
||||
stopEntry(entry, '转发失败:' + String((e && e.message) || e));
|
||||
if (res.headersSent || !/^(GET|HEAD)$/.test(req.method)) return false;
|
||||
await new Promise((r) => setTimeout(r, 400)); // 给内核回收旧 listen 套接字留个极短窗口
|
||||
const m2 = await waitReady(entry.pageDec);
|
||||
if (!m2 || !m2.entry) return false;
|
||||
try {
|
||||
await tryForward(m2.entry, req, res, innerPath);
|
||||
return true;
|
||||
} catch (_) { return false; }
|
||||
}
|
||||
}
|
||||
|
||||
// 槽位过期:外部(非 officecli)写盘改的是文件,watch 内存里的渲染不感知 → 导航时比对指纹回收重渲染
|
||||
function fileChanged(entry) {
|
||||
try {
|
||||
const st = fs.statSync(entry.file);
|
||||
return st.mtimeMs !== entry.mtimeMs || st.size !== entry.size;
|
||||
} catch (_) { return false; }
|
||||
}
|
||||
|
||||
// 浏览器导航请求判定:只有地址栏/iframe 直开页面带 text/html
|
||||
function isNav(req) {
|
||||
return req.method === 'GET' && /text\/html/.test(String(req.headers.accept || ''));
|
||||
}
|
||||
|
||||
// 数据请求(资源/API/SSE/Referer 兜底):按 Referer 找回来源页面
|
||||
function refererRel(req) {
|
||||
const ref = req.headers.referer || req.headers.referrer || '';
|
||||
if (!ref) return null;
|
||||
try {
|
||||
const rp = decodeURIComponent(new URL(ref).pathname);
|
||||
if (!rp.startsWith(PREFIX + '/')) return null;
|
||||
return rp.slice(PREFIX.length);
|
||||
} catch (_) { return null; }
|
||||
}
|
||||
|
||||
// ---------- 编辑命令的事后一脚 ----------
|
||||
// office 封装层改动成功后 fire-and-forget 打这里(本地没有沙箱,原生通知本来就能到 watch;
|
||||
// 这一脚是无害的补强,也让行为与服务器保持一致)。
|
||||
function handleTouch(req, res) {
|
||||
let body = '';
|
||||
req.on('data', (d) => { body += d; if (body.length > 4096) req.destroy(); });
|
||||
req.on('end', () => {
|
||||
let f = '';
|
||||
try { f = String(JSON.parse(body || '{}').file || ''); } catch (_) {}
|
||||
let hit = null;
|
||||
if (f) {
|
||||
const rp = path.resolve(f);
|
||||
for (const s of slots.values()) if (s.file === rp) { hit = s; break; }
|
||||
}
|
||||
if (hit && hit.ready) {
|
||||
hit.lastUsed = Date.now();
|
||||
notifySwitch(hit);
|
||||
try { const st = fs.statSync(hit.file); hit.mtimeMs = st.mtimeMs; hit.size = st.size; } catch (_) {}
|
||||
res.writeHead(200, { 'content-type': 'application/json' }).end('{"touched":true}');
|
||||
} else {
|
||||
res.writeHead(200, { 'content-type': 'application/json' }).end('{"touched":false}');
|
||||
}
|
||||
});
|
||||
req.on('error', () => {});
|
||||
}
|
||||
|
||||
// ---------- 路由 ----------
|
||||
const server = http.createServer((req, res) => {
|
||||
route(req, res).catch((e) => {
|
||||
log('请求失败 ' + req.url + ':' + ((e && e.message) || e));
|
||||
if (!res.headersSent) res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' }).end('预览网关内部错误');
|
||||
});
|
||||
});
|
||||
|
||||
async function route(req, res) {
|
||||
if (req.method === 'POST' && req.url.split('?')[0] === '/__pv-touch') return handleTouch(req, res);
|
||||
|
||||
let u;
|
||||
try { u = decodeURIComponent((req.url || '/').split('?')[0]); } catch (_) { res.writeHead(400).end('bad path'); return; }
|
||||
|
||||
if (req.method === 'GET' && u === '/gateway-healthz') {
|
||||
const body = JSON.stringify({ ok: true, prefix: PREFIX, slots: slots.size, bin: resolveBin() });
|
||||
res.writeHead(200, { 'content-type': 'application/json' }).end(body);
|
||||
return;
|
||||
}
|
||||
|
||||
if (u === PREFIX + '/' || u.startsWith(PREFIX + '/')) {
|
||||
const rel = u.slice(PREFIX.length) || '/';
|
||||
const rr = rel.replace(/\/+$/, ''); // 去掉尾斜杠后的页面路径
|
||||
const segs = rel.split('/').filter(Boolean);
|
||||
const sid = segs.shift() || '';
|
||||
const wantSlash = !/\/$/.test(u); // 缺尾斜杠:相对资源会解析错,要补 301
|
||||
|
||||
// HEAD = 前端预览窗的「这份文档能不能预览」探针。存在性只在本地按文件系统回答,绝不上探 watch;
|
||||
// 但回 200 前要等槽位就绪(有上限):冷启动的首次渲染很贵,这里等掉,iframe 一挂上就是渲染好的页面。
|
||||
if (req.method === 'HEAD') {
|
||||
const t = await guard(sid, segs.join('/'));
|
||||
if (t) {
|
||||
if (!resolveBin()) {
|
||||
res.writeHead(200, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store', 'content-length': '0' }).end();
|
||||
return;
|
||||
}
|
||||
await warmSlot(rel, t);
|
||||
res.writeHead(200, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store', 'content-length': '0' }).end();
|
||||
return;
|
||||
}
|
||||
if (EXTS.has(path.extname(rr).toLowerCase())) return notFound(res);
|
||||
}
|
||||
|
||||
if (isNav(req)) {
|
||||
// 导航请求 = 用户正盯着这一刻:绝不为启动/自愈阻塞首字节。未就绪 → 中转页 + 后台热槽。
|
||||
const t = await guard(sid, segs.join('/'));
|
||||
if (!t) return notFound(res);
|
||||
if (!resolveBin()) return installPage(res);
|
||||
const m = matchPage(rr);
|
||||
if (!m || !m.entry.ready) {
|
||||
startWatch(t).catch(() => {});
|
||||
return loading(res);
|
||||
}
|
||||
if (fileChanged(m.entry)) {
|
||||
stopEntry(m.entry, '外部变更');
|
||||
startWatch(t).catch(() => {});
|
||||
return loading(res);
|
||||
}
|
||||
if (m.exact && wantSlash) { res.writeHead(301, { location: (req.url || u) + '/' }).end(); return; }
|
||||
const cut = PREFIX.length + m.entry.pageDec.length;
|
||||
try {
|
||||
await tryForward(m.entry, req, res, u.length > cut ? u.slice(cut) : '/', NAV_TIMEOUT_MS);
|
||||
m.entry.navTimeouts = 0;
|
||||
return;
|
||||
} catch (e) {
|
||||
const msg = String((e && e.message) || e);
|
||||
// 超时 ≠ 死:大文档首次渲染可能超过 5s。单次超时保留槽位,连续几次才判死重启。
|
||||
m.entry.navTimeouts = /超时/.test(msg) ? (m.entry.navTimeouts || 0) + 1 : NAV_TIMEOUT_RETRIES;
|
||||
if (m.entry.navTimeouts >= NAV_TIMEOUT_RETRIES) {
|
||||
stopEntry(m.entry, msg);
|
||||
startWatch(t).catch(() => {});
|
||||
}
|
||||
if (!res.headersSent) return loading(res);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// 非导航(页面资源/API/SSE):等就绪槽位后自愈转发——用户看不见这些请求,值得原地救活
|
||||
const m = await waitReady(rel);
|
||||
if (m && m.entry) {
|
||||
if (m.exact && wantSlash) { res.writeHead(301, { location: (req.url || u) + '/' }).end(); return; }
|
||||
const cut = PREFIX.length + m.entry.pageDec.length;
|
||||
if (await forwardHealed(m.entry, req, res, u.length > cut ? u.slice(cut) : '/')) return;
|
||||
return fail502(res);
|
||||
}
|
||||
}
|
||||
|
||||
// vendor 页面把交互 API 与「自身最新 HTML」硬编码成根绝对路径(/、/events、/api/*):
|
||||
// 按 Referer 找回来源页,原路径原样转发(不剥页面前缀)。`/` 尤其关键——回 404 页面会
|
||||
// 判定自身过期并 location.reload(),用户看到的就是白屏后重新加载。
|
||||
const rrel = refererRel(req);
|
||||
if (rrel) {
|
||||
const mv = await waitReady(rrel);
|
||||
if (mv && mv.entry) {
|
||||
if (await forwardHealed(mv.entry, req, res, u)) return;
|
||||
return fail502(res);
|
||||
}
|
||||
}
|
||||
notFound(res);
|
||||
}
|
||||
|
||||
// 闲置回收:watch 是常驻进程,不回收会一直占着内存与端口(与服务器一致 6h)。
|
||||
const idleTimer = setInterval(() => {
|
||||
const now = Date.now();
|
||||
for (const s of [...slots.values()]) {
|
||||
if (!s.conns && now - s.lastUsed > IDLE_MS) stopEntry(s, '闲置回收');
|
||||
}
|
||||
for (const [k, v] of cooldown) if (v <= now) cooldown.delete(k);
|
||||
}, 60000);
|
||||
idleTimer.unref();
|
||||
|
||||
// 带外写盘兜底 + 页内编辑(POST /api/send 实测只落盘不推事件)的唯一刷新通道:
|
||||
// 开着页面时比对 mtime,变了就对活槽位 POST /api/switch 就地重读。
|
||||
const pollTimer = setInterval(() => {
|
||||
const now = Date.now();
|
||||
for (const s of [...slots.values()]) {
|
||||
let st = null;
|
||||
try { st = fs.statSync(s.file); } catch (_) {}
|
||||
if (!st) { stopEntry(s, '文件已删除'); continue; } // 会话被删/文件被移走
|
||||
if (!s.conns) continue; // 没人开着页面:导航侧的指纹门会兜住
|
||||
if (!s.ready || st.mtimeMs === s.mtimeMs) continue;
|
||||
if (now - (s.lastNative || 0) < 10000) { s.mtimeMs = st.mtimeMs; s.size = st.size; continue; }
|
||||
s.mtimeMs = st.mtimeMs;
|
||||
s.size = st.size;
|
||||
notifySwitch(s);
|
||||
}
|
||||
}, 2000);
|
||||
pollTimer.unref();
|
||||
|
||||
function shutdown() {
|
||||
for (const s of [...slots.values()]) stopEntry(s);
|
||||
process.exit(0);
|
||||
}
|
||||
process.on('SIGTERM', shutdown);
|
||||
process.on('SIGINT', shutdown);
|
||||
// 退出/崩溃时别把 spawn 出去的 watch 养成孤儿
|
||||
process.on('exit', () => { for (const s of [...slots.values()]) killWatch(s); });
|
||||
process.on('unhandledRejection', (e) => log('未处理的 Promise 拒绝:' + ((e && e.message) || e)));
|
||||
|
||||
server.listen(PORT, HOST, () => {
|
||||
log('预览网关 listening ' + HOST + ':' + PORT + ' prefix=' + PREFIX + '/' +
|
||||
' tasks=' + TASKS_ROOT + ' skills=' + SKILLS_ROOT + ' slots=' + SLOTS);
|
||||
});
|
||||
Executable
+1166
File diff suppressed because it is too large
Load Diff
Executable
+116
@@ -0,0 +1,116 @@
|
||||
#!/bin/sh
|
||||
# local/stop.sh —— 停掉本机 local 模式拉起来的 agent-core 与 MCP 子进程。
|
||||
#
|
||||
# 正常停法就是 ./local/stop.sh:启动器默认是后台跑的(start.sh 拉起后就返回)。
|
||||
# 前台模式(AGENT_LOCAL_DETACH=0)下 Ctrl-C / 关窗口也能停。
|
||||
# 但终端可能被关掉、进程可能是从别处起的——那时就只能按 pid / 端口找。
|
||||
#
|
||||
# 关键点:启动器是父进程(启动器 → core + 3/4 个 MCP),只杀 core 会被它重新拉起来
|
||||
# (那是「重启」的语义)。所以必须先停启动器,停不掉再按端口硬收。
|
||||
# 幂等:没在运行时直说,不报错。
|
||||
set -u
|
||||
|
||||
HERE=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
||||
RUNTIME="$HERE/.runtime"
|
||||
PIDFILE="$RUNTIME/supervisor.pid"
|
||||
|
||||
PORT="${PORT:-8090}"
|
||||
# 与 start.sh 的默认值一致;用 MCP_*_PORT 改过端口时这里也要跟着改(否则兜底那步找不到它们)。
|
||||
MCP_PORTS="${MCP_WEB_PORT:-8091} ${MCP_IMAGE_PORT:-8092} ${MCP_VIDEO_PORT:-8093} ${MCP_ASR_PORT:-8094}"
|
||||
# 预览网关端口是启动时从 3100 往后找的第一个空闲口,只能读它写下的记录。
|
||||
pv_port=$(cat "$RUNTIME/preview.port" 2>/dev/null || printf '')
|
||||
case "$pv_port" in ''|*[!0-9]*) pv_port='3100';; esac
|
||||
|
||||
stopped=0
|
||||
|
||||
say() { printf '==> %s\n' "$*"; }
|
||||
|
||||
# 某个端口上处于 LISTEN 的进程 pid(没有 lsof 就返回空)。
|
||||
pids_on_port() {
|
||||
command -v lsof >/dev/null 2>&1 || return 0
|
||||
lsof -nP -tiTCP:"$1" -sTCP:LISTEN 2>/dev/null
|
||||
}
|
||||
|
||||
stop_pid() {
|
||||
# $1 pid $2 说明
|
||||
kill -TERM "$1" 2>/dev/null || return 0
|
||||
say "停止$2(pid $1)"
|
||||
stopped=1
|
||||
}
|
||||
|
||||
wait_gone() {
|
||||
# $1 pid,最多等 10 秒
|
||||
i=0
|
||||
while [ "$i" -lt 20 ]; do
|
||||
kill -0 "$1" 2>/dev/null || return 0
|
||||
sleep 0.5 2>/dev/null || sleep 1
|
||||
i=$((i + 1))
|
||||
done
|
||||
}
|
||||
|
||||
# 1) 首选:启动器自己写的 pid 文件(最准,也最快)。
|
||||
if [ -f "$PIDFILE" ]; then
|
||||
pid=$(cat "$PIDFILE" 2>/dev/null || printf '')
|
||||
case "$pid" in ''|*[!0-9]*) pid='';; esac
|
||||
if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null; then
|
||||
stop_pid "$pid" '启动器'
|
||||
wait_gone "$pid"
|
||||
if kill -0 "$pid" 2>/dev/null; then
|
||||
say '启动器 10 秒内没退出,强制结束'
|
||||
kill -KILL "$pid" 2>/dev/null || true
|
||||
fi
|
||||
sleep 1
|
||||
fi
|
||||
rm -f "$PIDFILE"
|
||||
fi
|
||||
|
||||
# 2) pid 文件丢了(终端被强杀、目录被清过):从 core 的父进程认出启动器。
|
||||
# 按「谁是 8090 的父进程」找,而不是按启动命令的路径拼写去 pgrep——
|
||||
# 同机可能有别的 clone,靠路径匹配容易误杀或不匹配(实测 `sh ./local/start.sh` 是相对路径)。
|
||||
if [ "$stopped" = 0 ]; then
|
||||
for pid in $(pids_on_port "$PORT"); do
|
||||
ppid=$(ps -o ppid= -p "$pid" 2>/dev/null | tr -d ' ')
|
||||
case "$ppid" in ''|0|1|*[!0-9]*) continue;; esac
|
||||
if ps -o command= -p "$ppid" 2>/dev/null | grep -q 'start\.sh'; then
|
||||
stop_pid "$ppid" '启动器(按 core 的父进程识别)'
|
||||
wait_gone "$ppid"
|
||||
if kill -0 "$ppid" 2>/dev/null; then
|
||||
say '启动器 10 秒内没退出,强制结束'
|
||||
kill -KILL "$ppid" 2>/dev/null || true
|
||||
fi
|
||||
fi
|
||||
done
|
||||
[ "$stopped" = 1 ] && sleep 2
|
||||
fi
|
||||
|
||||
# 3) 兜底:还占着端口的直接收(启动器已经死了,剩下的都是孤儿)。
|
||||
for p in "$PORT" $MCP_PORTS "$pv_port"; do
|
||||
for pid in $(pids_on_port "$p"); do
|
||||
stop_pid "$pid" "端口 $p 上的进程"
|
||||
done
|
||||
done
|
||||
[ "$stopped" = 1 ] && sleep 2
|
||||
|
||||
# 4) 收尾:仍占着端口的强制结束,避免下次启动被判「端口被占用」。
|
||||
for p in "$PORT" $MCP_PORTS "$pv_port"; do
|
||||
for pid in $(pids_on_port "$p"); do
|
||||
kill -KILL "$pid" 2>/dev/null || true
|
||||
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
|
||||
say '已停止'
|
||||
else
|
||||
say "没有在运行(${PORT}、MCP 端口 ${MCP_PORTS}、预览端口 $pv_port 都空闲)"
|
||||
fi
|
||||
@@ -172,7 +172,7 @@ response_format=url
|
||||
url: "http://mcp_image_task:3000/mcp"
|
||||
headers:
|
||||
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"
|
||||
mode: skill
|
||||
```
|
||||
@@ -258,7 +258,7 @@ curl -s -X POST http://localhost:8082/mcp \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "Accept: application/json, text/event-stream" \
|
||||
-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 "Mcp-Session-Id: $SESSION" \
|
||||
-d '{
|
||||
|
||||
+7
-5
@@ -25,6 +25,7 @@ skills/
|
||||
├── run.py # 技能主入口(Python 脚本,推荐)或 run.sh
|
||||
├── requirements.txt # Python 依赖(可选,若需要第三方包)
|
||||
├── install.sh # 系统级依赖安装脚本(可选,如 apt-get)
|
||||
├── AGENTS.md # 该技能的排错命令(可选;core 不读,只在报错信息里被指向)
|
||||
└── ... # 其他技能相关文件(如字体、模板等)
|
||||
```
|
||||
|
||||
@@ -163,12 +164,13 @@ def main():
|
||||
示例 `requirements.txt`:
|
||||
|
||||
```
|
||||
requests==2.28.1
|
||||
beautifulsoup4==4.11.1
|
||||
requests
|
||||
beautifulsoup4
|
||||
```
|
||||
|
||||
- 依赖安装使用 `pip install --target`,不会污染系统全局;镜像已带的包不会重复装。
|
||||
- 所有技能**共享**同一个 `deps` 目录,请注意版本冲突(后装的覆盖先装的)。建议锁定精确版本。
|
||||
- 所有技能**共享**同一个 `deps` 目录,请注意版本冲突(后装的覆盖先装的)。
|
||||
- 默认**不写版本号**:init 用 `pip install --no-index --dry-run <行>` 探测是否已满足,写死版本而镜像/外挂层里是别的版本时探测失败,会往 `deps` 再装一份,而 `PYTHONPATH` 优先于系统 site-packages,等于用旧版本遮蔽镜像包。确有兼容约束才 pin(如 `weasyprint==65.1` 与 pydyf 的编码兼容)。
|
||||
- 运行期 skills 目录只读;若上线后经 UI 改了 `requirements.txt`,需重启(`docker compose up -d`)触发重新 init,否则该技能会因依赖未就绪而失败。
|
||||
|
||||
### 5.2 系统级依赖
|
||||
@@ -288,7 +290,7 @@ A:确保 `requirements.txt` 存在且列出了所有需要的包,并检查 `
|
||||
A:检查网络连接和 pip 源是否可用,查看 Skill Manager 输出的错误日志。
|
||||
|
||||
**Q:多个技能依赖冲突如何解决?**
|
||||
A:目前所有技能共享同一个 `deps` 目录,建议锁定精确版本,或考虑将冲突的技能拆分到不同的环境中(未来可能支持隔离)。
|
||||
A:目前所有技能共享同一个 `deps` 目录,后装的覆盖先装的。真遇到冲突才给冲突的包 pin(pin 会让离线探测失败,把该版本强行装进 `deps` 并遮蔽镜像包);能升到共同版本更好。
|
||||
|
||||
---
|
||||
|
||||
@@ -296,7 +298,7 @@ A:目前所有技能共享同一个 `deps` 目录,建议锁定精确版本
|
||||
|
||||
查看现有的 `x2pdf` 技能(位于 `skills/x2pdf/`)可以了解一个较为完整的实现,包括如何自带声明 Python 依赖与系统级依赖(不假设镜像预烘)、按扩展名分派渲染后端、参数化版式 CSS 等。但请根据自身技能的实际需求进行设计,不必拘泥于该示例。
|
||||
|
||||
图像处理类需求可参考 `skills/image-process/`:它演示了一个纯 Python + 预装 Pillow 的实现(转换/缩放/裁剪/压缩/水印/切片/拼图,无 requirements.txt,仅靠 install.sh 保证中文字体),并明确区分“确定性图像处理”与“AI 生成/修图”的能力边界。
|
||||
图像处理类需求可参考 `skills/image-process/`:它演示了一个纯 Python + 预装 Pillow 的实现(转换/缩放/裁剪/压缩/水印/切片/拼图,Python 依赖只列 Pillow,中文字体由 install.sh 保证),并明确区分“确定性图像处理”与“AI 生成/修图”的能力边界。
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
# document-photo-to-pdf
|
||||
|
||||
以下命令仅为示例,具体以本机平台实际情况为准。
|
||||
|
||||
## ModuleNotFoundError: numpy / PIL / fitz
|
||||
|
||||
把依赖装进 `$AGENT_SKILLS_DEPS`。
|
||||
|
||||
```sh
|
||||
python3 -m pip install --upgrade --target "$AGENT_SKILLS_DEPS" -r "$(dirname "$AGENT_SKILLS_DEPS")/document-photo-to-pdf/requirements.txt"
|
||||
```
|
||||
|
||||
`fitz` 是 `pymupdf` 的 import 名,`pypdfium2` 不用装;没有 `python3` 先装运行时(Windows 常是 `python` / `py`)。
|
||||
@@ -39,7 +39,7 @@ input_schema:
|
||||
|
||||
```json
|
||||
{"ok":true,"summary":"3 页已生成;1 页建议在审核页确认;原始页图见 out/","pdf":"合同_校正.pdf","images":["out/合同_校正-01.png","out/合同_校正-02.png","out/合同_校正-03.png"]}
|
||||
访问地址:https://agent.ai.foresh.com/app/task-20261023-001/doc-review/
|
||||
访问地址:<站点地址>/app/task-20261023-001/doc-review/
|
||||
```
|
||||
|
||||
审核页可拖角、旋转、删页/排序、改纸张与清晰度;改动后点「重新生成 PDF」覆盖同名文件。
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
# 这份文件主要给「本地端」(local/)用:本机 python 缺包时,启动器或模型自己可以按它补装。
|
||||
#
|
||||
# 刻意不写版本号:服务端 agent-executor-init 的判定是
|
||||
# python3 -m pip install --no-index --dry-run <本行>
|
||||
# 退出码 0 即视为已满足、直接跳过装包(executor 镜像已烘了 numpy/Pillow/pymupdf)。
|
||||
# 一旦写了 pin 而镜像里是别的版本,探测就会失败 → 真的往 skills/deps 装一份老版本,
|
||||
# 而 PYTHONPATH 优先于系统 site-packages,等于用外挂层遮蔽镜像版,会牵连其它技能。
|
||||
#
|
||||
# pypdfium2 是 check.py 里 fitz 缺失时的兜底渲染器,不是必需,故不声明。
|
||||
|
||||
numpy
|
||||
Pillow
|
||||
pymupdf
|
||||
@@ -864,7 +864,11 @@ def process(args, t0):
|
||||
if not state_ok:
|
||||
warnings.append("state 文件写入失败:%s" % state_path)
|
||||
|
||||
if checks.get("ok") is False:
|
||||
if checks.get("ok") is None:
|
||||
# 自检根本没跑(无 PDF 渲染后端等):不能让它伪装成「建议确认」——
|
||||
# 那种情况下页面压根没过边缘/短边检验,模型和用户都得知道判据缺失。
|
||||
summary = "%d 页已生成;PDF 自检未能执行,请在审核页人工确认" % len(ordered_pages)
|
||||
elif checks.get("ok") is False:
|
||||
summary = "%d 页已生成;自检有未通过项" % len(ordered_pages)
|
||||
elif needs:
|
||||
summary = "%d 页已生成;%d 页建议在审核页确认" % (
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
# image-process
|
||||
|
||||
以下命令仅为示例,具体以本机平台实际情况为准。
|
||||
|
||||
## ModuleNotFoundError: No module named 'PIL'
|
||||
|
||||
把依赖装进 `$AGENT_SKILLS_DEPS`。
|
||||
|
||||
```sh
|
||||
python3 -m pip install --upgrade --target "$AGENT_SKILLS_DEPS" -r "$(dirname "$AGENT_SKILLS_DEPS")/image-process/requirements.txt"
|
||||
```
|
||||
|
||||
## 中文水印缺少字体
|
||||
|
||||
传 `font` 参数,指向本机任意中文字体文件(ttf/ttc)。
|
||||
|
||||
```json
|
||||
{"action":"watermark","input":"a.jpg","text":"机密","font":"<本机中文字体路径>"}
|
||||
```
|
||||
|
||||
找字体:Linux `fc-list :lang=zh`;macOS `ls /System/Library/Fonts`;Windows `C:\Windows\Fonts\msyh*`。
|
||||
@@ -0,0 +1,7 @@
|
||||
# 本技能只用 Pillow(Image/ImageDraw/ImageFont/ImageOps)。
|
||||
#
|
||||
# 这份文件主要给「本地端」(local/)用:本机 python 缺包时按它补装。
|
||||
# 不写版本号的原因见 skills/document-photo-to-pdf/requirements.txt 顶部的说明:
|
||||
# 服务端 init 用 `pip install --no-index --dry-run` 探测,pin 到与镜像不同的版本会反向遮蔽镜像包。
|
||||
|
||||
Pillow
|
||||
@@ -249,7 +249,8 @@ def action_watermark(img, fmt, args):
|
||||
if font_path:
|
||||
font = ImageFont.truetype(font_path, font_size)
|
||||
elif need_cjk:
|
||||
raise ValueError('中文水印缺少字体:请传 font 参数(TTF/TTC 路径),或确认系统已装文泉驿/Noto 字体')
|
||||
raise ValueError('中文水印缺少字体:传 font 参数(TTF/TTC 路径);本机环境见 %s'
|
||||
% (Path(__file__).resolve().parent / 'AGENTS.md'))
|
||||
else:
|
||||
try:
|
||||
font = ImageFont.load_default(size=font_size)
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
# office
|
||||
|
||||
以下命令仅为示例,具体以本机平台实际情况为准(自行判断路径、可执行名、分隔符)。
|
||||
|
||||
## office: command not found
|
||||
|
||||
入口不在 PATH:建一次软链,之后一直能用。
|
||||
|
||||
```sh
|
||||
mkdir -p "$HOME/.local/bin"
|
||||
ln -sfn "$(dirname "$AGENT_SKILLS_DEPS")/office/scripts/office" "$HOME/.local/bin/office"
|
||||
```
|
||||
|
||||
## office.core binary missing
|
||||
|
||||
按本机平台下载对应资产到 `bin/officecli`(Windows 存成 `bin/officecli.exe`),再 `chmod +x`。
|
||||
|
||||
```sh
|
||||
SK="$(dirname "$AGENT_SKILLS_DEPS")/office"
|
||||
curl -fL -o "$SK/bin/officecli" \
|
||||
https://github.com/iOfficeAI/OfficeCLI/releases/latest/download/officecli-<平台>-<架构>
|
||||
chmod +x "$SK/bin/officecli"
|
||||
```
|
||||
|
||||
资产名是 `{mac,linux,win}-{x64,arm64}`,如 `officecli-mac-arm64`、`officecli-linux-x64`、`officecli-win-x64.exe`;
|
||||
musl 系统(Alpine)用 `officecli-linux-alpine-{x64,arm64}`。`uname -sm` 可判断平台与架构。
|
||||
@@ -92,7 +92,7 @@ try {
|
||||
}
|
||||
if (r.error) {
|
||||
if (r.error.code === 'ENOENT') {
|
||||
err('office.core binary missing: ' + BIN + ' (skill asset not fetched: docker compose up -d agent-executor-init to retry, or place it per skills/office/install.sh)');
|
||||
err('office.core binary missing: ' + BIN + ' (install per ' + path.resolve(__dirname, '..', 'AGENTS.md') + ')');
|
||||
}
|
||||
err(String(r.error.message || r.error));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
# x2pdf
|
||||
|
||||
以下命令仅为示例,具体以本机平台实际情况为准。
|
||||
|
||||
## ModuleNotFoundError: markdown
|
||||
|
||||
把依赖装进 `$AGENT_SKILLS_DEPS`。
|
||||
|
||||
```sh
|
||||
python3 -m pip install --upgrade --target "$AGENT_SKILLS_DEPS" -r "$(dirname "$AGENT_SKILLS_DEPS")/x2pdf/requirements.txt"
|
||||
```
|
||||
|
||||
## 没有可用的 PDF 排版能力
|
||||
|
||||
文本类有三个后端可退,从便宜到贵补,别一次全装:
|
||||
|
||||
- 浏览器:有 Chrome / Chromium / Edge 就自动用,通常不用装
|
||||
- LibreOffice:Office 类(docx/xlsx/pptx)必装——Linux `apt install libreoffice`;macOS `brew install --cask libreoffice`;Windows `winget install TheDocumentFoundation.LibreOffice`
|
||||
- WeasyPrint:先装上面的 Python 包,再补系统库 pango/cairo(见下节)
|
||||
|
||||
系统级安装几百 MB,先跟用户说清代价,由他决定装还是接受降级。
|
||||
|
||||
## could not import some external libraries
|
||||
|
||||
系统库没到位,不是 Python 包的问题:Linux `apt install libpango-1.0-0 libpangocairo-1.0-0 libcairo2`;macOS `brew install pango`;Windows 补 GTK 运行库,装不上就跳过。
|
||||
|
||||
装完验证:
|
||||
|
||||
```sh
|
||||
python3 -c "import weasyprint; print(weasyprint.__version__)"
|
||||
```
|
||||
|
||||
## 输出带「排版降级」
|
||||
|
||||
无页码或边距偏差不是失败,是后端不全,按需补。
|
||||
@@ -37,8 +37,8 @@ output_schema:
|
||||
|
||||
统一 PDF 转换入口,按扩展名自动分派两条渲染路径:
|
||||
|
||||
- **md / txt / html → WeasyPrint**(CSS 排版,字体走 fontconfig,中文用系统文泉驿/Noto,无需字体文件)
|
||||
- **docx / xlsx / pptx / odt / ods / odp → LibreOffice headless**(忠于原文档版式,`page`/`css` 参数不生效)
|
||||
- **md / txt / html → 渲染成 PDF**(CSS 排版,字体走系统 fontconfig,中文用系统文泉驿/Noto,无需字体文件)
|
||||
- **docx / xlsx / pptx / odt / ods / odp → 按原文档版式转换**(`page`/`css` 参数不生效)
|
||||
|
||||
### Markdown 输入(`.md` / `.markdown`)
|
||||
- 标准语法之外,支持表格(管道语法)、围栏代码块(```/~~~)、脚注、定义列表、
|
||||
|
||||
@@ -4,4 +4,7 @@
|
||||
# 选 65.1:晚于 pydyf 0.12 发布,对 pydyf 0.11/0.12 兼容性经上游验证;
|
||||
# 系统要求(Pango>=1.44)与本技能 install.sh 声明一致。
|
||||
weasyprint==65.1
|
||||
markdown==3.6
|
||||
# markdown 不锁版:只用 markdown(text, extensions=['extra','toc']),3.x 全系稳定。
|
||||
# 锁了反而有害——服务端 init 用 `pip install --no-index --dry-run` 探测,写死版本与镜像里
|
||||
# 已有的不一致时会往 skills/deps 再装一份,而 PYTHONPATH 优先于系统 site-packages。
|
||||
markdown
|
||||
|
||||
+139
-9
@@ -3,13 +3,19 @@
|
||||
x2pdf 技能主入口:通用 PDF 转换。
|
||||
|
||||
分派策略(按输入文件扩展名):
|
||||
- .md / .markdown / .txt / .html / .htm → WeasyPrint 渲染
|
||||
- .md / .markdown / .txt / .html / .htm → 依次尝试 WeasyPrint / 无头浏览器 / LibreOffice
|
||||
三者都是本机可能没有的渲染后端:WeasyPrint 缺包或缺 pango/cairo 时不可用,
|
||||
浏览器(Chrome/Chromium/Edge)不需要任何 Python 依赖,保真度介于两者之间
|
||||
- .docx / .xlsx / .pptx / .odt / .ods / .odp → LibreOffice headless 转换
|
||||
|
||||
依赖不假设镜像预烘:Python 包由 requirements.txt 声明,系统库由 install.sh 就绪校验。
|
||||
LibreOffice 与浏览器的定位不只看 PATH:macOS 的 app bundle 与 Windows 的安装目录都不进 PATH,
|
||||
which() 找不到不等于没装(见 find_soffice / find_browser)。
|
||||
中文字体走 fontconfig(系统文泉驿/Noto),技能不携带字体文件。
|
||||
"""
|
||||
import contextlib
|
||||
import html as html_mod
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
@@ -27,6 +33,51 @@ SUPPORTED_EXTS = TEXT_EXTS | OFFICE_EXTS
|
||||
|
||||
PAGE_DEFAULTS = {'size': 'A4', 'margin': '20mm', 'font_size': '10.5pt'}
|
||||
|
||||
SKILL_DIR = Path(__file__).resolve().parent
|
||||
|
||||
|
||||
def find_soffice():
|
||||
"""定位 LibreOffice 可执行文件。
|
||||
PATH 优先(服务器/apt 装的都在);再探 macOS 的 app bundle 与 Windows 的安装目录——
|
||||
这两个位置正常安装都不进 PATH,只用 shutil.which() 会把「装了」误判成「没装」。"""
|
||||
for name in ('soffice', 'libreoffice'):
|
||||
p = shutil.which(name)
|
||||
if p:
|
||||
return p
|
||||
for c in ('/Applications/LibreOffice.app/Contents/MacOS/soffice',
|
||||
str(Path.home() / 'Applications/LibreOffice.app/Contents/MacOS/soffice'),
|
||||
r'C:\Program Files\LibreOffice\program\soffice.exe',
|
||||
r'C:\Program Files (x86)\LibreOffice\program\soffice.exe'):
|
||||
if Path(c).is_file():
|
||||
return c
|
||||
return None
|
||||
|
||||
|
||||
def find_browser():
|
||||
"""定位支持 --headless --print-to-pdf 的浏览器(Chrome / Chromium / Edge)。
|
||||
不要求用户为了转 PDF 装 Python 侧渲染栈:pango 在老系统上只能现编。
|
||||
同 find_soffice:macOS app bundle 与 Windows 安装目录都不进 PATH。"""
|
||||
for name in ('google-chrome', 'google-chrome-stable', 'chromium', 'chromium-browser',
|
||||
'microsoft-edge', 'msedge'):
|
||||
p = shutil.which(name)
|
||||
if p:
|
||||
return p
|
||||
for c in ('/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
|
||||
'/Applications/Chromium.app/Contents/MacOS/Chromium',
|
||||
'/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge',
|
||||
str(Path.home() / 'Applications/Google Chrome.app/Contents/MacOS/Google Chrome'),
|
||||
r'C:\Program Files\Google\Chrome\Application\chrome.exe',
|
||||
r'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe',
|
||||
r'C:\Program Files\Microsoft\Edge\Application\msedge.exe',
|
||||
r'C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe'):
|
||||
if Path(c).is_file():
|
||||
return c
|
||||
return None
|
||||
|
||||
|
||||
def req_hint():
|
||||
return '本机环境: %s' % (SKILL_DIR / 'AGENTS.md')
|
||||
|
||||
# 默认样式:黑白友好、打印向。字号用 em 相对值,整体缩放只依赖 html font-size
|
||||
# (由 page.font_size 参数注入),因此压单页只需调小字号/边距。
|
||||
DEFAULT_CSS = """
|
||||
@@ -136,9 +187,7 @@ def build_document(title, body_html):
|
||||
|
||||
|
||||
def convert_text_pdf(input_path, output_path, css_arg, page_arg):
|
||||
"""md/txt/html → WeasyPrint"""
|
||||
from weasyprint import CSS, HTML
|
||||
|
||||
"""md/txt/html → PDF。返回一句后端提示(正常走 WeasyPrint 时为空串)。"""
|
||||
ext = input_path.suffix.lower()
|
||||
text = input_path.read_text(encoding='utf-8', errors='replace')
|
||||
user_css = None
|
||||
@@ -157,7 +206,10 @@ def convert_text_pdf(input_path, output_path, css_arg, page_arg):
|
||||
sheets = [s for s in (page_css(page_arg, with_defaults=False), user_css) if s]
|
||||
else:
|
||||
if ext in MD_EXTS:
|
||||
import markdown
|
||||
try:
|
||||
import markdown
|
||||
except ImportError:
|
||||
raise RuntimeError('缺 Python 包 markdown,无法解析 Markdown;%s' % req_hint())
|
||||
# extra 已含 tables/fenced_code/footnotes/attr_list/md_in_html/sane_lists 等;
|
||||
# 不可再单独传其中的扩展名,否则 ExtensionAlreadyConfigured
|
||||
body = markdown.markdown(
|
||||
@@ -172,17 +224,92 @@ def convert_text_pdf(input_path, output_path, css_arg, page_arg):
|
||||
sheets.append(user_css)
|
||||
|
||||
output_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
try:
|
||||
# 导入失败时 WeasyPrint 会往 stdout 打一大段「could not import some external libraries」
|
||||
# (text/ffi.py 里裸 print),模型会把这段当成真错。降级是预期行为,噪声吞掉,
|
||||
# 由返回值那句 note 告知实际后端。
|
||||
sink = io.StringIO()
|
||||
with contextlib.redirect_stdout(sink), contextlib.redirect_stderr(sink):
|
||||
from weasyprint import CSS, HTML
|
||||
except (ImportError, OSError):
|
||||
# 缺 Python 包是 ImportError;装了包但缺它要 dlopen 的 libpango/libgobject 时是 OSError。
|
||||
# 两种都当作「本机没有 WeasyPrint」:先试浏览器(只需装了 Chrome 系),再回落 LibreOffice。
|
||||
browser = find_browser()
|
||||
if browser:
|
||||
return convert_html_browser(browser, document, output_path, base_url, sheets, ext)
|
||||
return convert_html_pdf(document, output_path, ext)
|
||||
# 注:stylesheets 参数只接受 CSS 对象,传字符串会被当成文件路径
|
||||
HTML(string=document, base_url=base_url).write_pdf(
|
||||
str(output_path), stylesheets=[CSS(string=s) for s in sheets] or None)
|
||||
return ''
|
||||
|
||||
|
||||
def inject_styles(document, sheets, base_url):
|
||||
"""把 CSS 与 base 标签塞进已有 HTML:浏览器后端只能吃单个文件。
|
||||
注入点是 </head>(其次 <body>),绝不能落到 doctype 前面——那会触发怪异模式。"""
|
||||
head = ''
|
||||
if base_url:
|
||||
head += '<base href="%s/">\n' % Path(base_url).resolve().as_uri()
|
||||
if sheets:
|
||||
head += '<style>\n%s\n</style>\n' % '\n'.join(sheets)
|
||||
if not head:
|
||||
return document
|
||||
m = re.search(r'</head\s*>', document, re.I) or re.search(r'<body[^>]*>', document, re.I)
|
||||
if m:
|
||||
return document[:m.start()] + head + document[m.start():]
|
||||
d = re.match(r'\s*<!doctype[^>]*>', document, re.I)
|
||||
if d:
|
||||
return document[:d.end()] + '\n' + head + document[d.end():]
|
||||
return head + document
|
||||
|
||||
|
||||
def convert_html_browser(browser, document, output_path, base_url, sheets, ext):
|
||||
"""HTML → 无头浏览器打印:WeasyPrint 不可用时的中间档。
|
||||
浏览器能完整解析 CSS(表格边框/底纹/分页),但页码是 WeasyPrint 的 CSS 计数器特性,
|
||||
这里不生效;@page 的 size/margin 视浏览器版本部分生效。"""
|
||||
output_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp_root = Path(tempfile.mkdtemp(prefix='x2pdf-browser-'))
|
||||
try:
|
||||
# 浏览器默认纸张是 Letter,WeasyPrint 默认 A4。文档自己没写 @page 时补上 A4,
|
||||
# 否则同一份 html 换后端就换纸型。
|
||||
if not any('@page' in s for s in sheets) and '@page' not in document:
|
||||
sheets = list(sheets) + ['@page { size: A4; }']
|
||||
src = tmp_root / 'document.html'
|
||||
src.write_text(inject_styles(document, sheets, base_url), encoding='utf-8')
|
||||
cmd = [browser, '--headless', '--disable-gpu', '--no-pdf-header-footer',
|
||||
'--virtual-time-budget=2000',
|
||||
'--print-to-pdf=%s' % str(output_path.resolve()), src.as_uri()]
|
||||
proc = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
|
||||
if not output_path.is_file() or output_path.stat().st_size == 0:
|
||||
detail = (proc.stderr or proc.stdout or '').strip().replace('\n', ' ')[:300]
|
||||
raise RuntimeError('PDF 生成失败(exit=%s):%s' % (proc.returncode, detail or '无输出'))
|
||||
finally:
|
||||
shutil.rmtree(tmp_root, ignore_errors=True)
|
||||
return '排版降级:无页码,尺寸/边距可能与预期有偏差'
|
||||
|
||||
|
||||
def convert_html_pdf(document, output_path, ext):
|
||||
"""HTML → LibreOffice:最后一道回落(浏览器也没有时)。
|
||||
代价是保真度:@page 的边距/页码与大部分 CSS 在 LibreOffice 的 HTML 导入里不生效,
|
||||
适合「拿到一份能看的 PDF」,不适合精确排版。"""
|
||||
if not find_soffice():
|
||||
raise RuntimeError('这台机器没有可用的 PDF 排版能力,无法转换 %s;%s' % (ext, req_hint()))
|
||||
tmp_root = Path(tempfile.mkdtemp(prefix='x2pdf-html-'))
|
||||
try:
|
||||
src = tmp_root / 'document.html'
|
||||
src.write_text(document, encoding='utf-8')
|
||||
convert_office_pdf(src, output_path)
|
||||
finally:
|
||||
shutil.rmtree(tmp_root, ignore_errors=True)
|
||||
return '排版降级:边距/页码与部分 CSS 不生效'
|
||||
|
||||
|
||||
def convert_office_pdf(input_path, output_path):
|
||||
"""docx/xlsx/pptx 等 → LibreOffice headless。
|
||||
每次用独立临时 UserInstallation/HOME,避免并发实例互踩共享配置。"""
|
||||
soffice = shutil.which('soffice') or shutil.which('libreoffice')
|
||||
soffice = find_soffice()
|
||||
if not soffice:
|
||||
raise FileNotFoundError('未找到 soffice/libreoffice,无法转换 Office 文档(需镜像预装)')
|
||||
raise FileNotFoundError('这台机器没有可用于转换 Office 文档的组件;%s' % req_hint())
|
||||
|
||||
output_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp_root = Path(tempfile.mkdtemp(prefix='x2pdf-office-'))
|
||||
@@ -203,7 +330,7 @@ def convert_office_pdf(input_path, output_path):
|
||||
generated = pdf_dir / (input_path.stem + '.pdf')
|
||||
if not generated.exists():
|
||||
detail = (proc.stderr or proc.stdout or '').strip().replace('\n', ' ')[:300]
|
||||
raise RuntimeError('LibreOffice 转换失败(exit=%s):%s' % (proc.returncode, detail or '无输出'))
|
||||
raise RuntimeError('文档转换失败(exit=%s):%s' % (proc.returncode, detail or '无输出'))
|
||||
shutil.move(str(generated), str(output_path))
|
||||
finally:
|
||||
shutil.rmtree(tmp_root, ignore_errors=True)
|
||||
@@ -239,6 +366,7 @@ def main():
|
||||
output_arg = args.get('output')
|
||||
output_path = Path(output_arg) if output_arg else input_path.with_suffix('.pdf')
|
||||
|
||||
note = ''
|
||||
try:
|
||||
if ext in OFFICE_EXTS:
|
||||
ignored = [k for k in ('css', 'page') if args.get(k)]
|
||||
@@ -246,12 +374,14 @@ def main():
|
||||
print('提示:Office 输入忽略参数 %s' % '、'.join(ignored))
|
||||
convert_office_pdf(input_path, output_path)
|
||||
else:
|
||||
convert_text_pdf(input_path, output_path, args.get('css'), args.get('page'))
|
||||
note = convert_text_pdf(input_path, output_path, args.get('css'), args.get('page'))
|
||||
except Exception as e:
|
||||
print('Error during conversion: %s' % e, file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
print('PDF generated: %s' % output_path.resolve())
|
||||
if note:
|
||||
print(note)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
@@ -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 盯上的概率
|
||||
- 断线自动重连,启动时自检每个端口可达性(不可达只告警不退出)
|
||||
|
||||
## 隧道协议
|
||||
|
||||
一条 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,225 @@
|
||||
#!/usr/bin/env node
|
||||
'use strict';
|
||||
// 通用反向隧道 · 本机端(家里那台)
|
||||
// 主动连服务器 → 收请求 → 按 Host 找本地端口 → 转发 → 流式回传
|
||||
//
|
||||
// 用法: node client.js [config.yml] 环境变量 TUNNEL_SERVER / TUNNEL_TOKEN 覆盖配置
|
||||
// 断线自动重连(指数退避 1s → 30s),心跳由服务端 ping 驱动,本端 ws 库自动回 pong。
|
||||
|
||||
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();
|
||||
|
||||
function log(...a) { console.log(new Date().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;
|
||||
|
||||
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;
|
||||
log(everLinked ? '已重新连接' : '已连接 ' + CFG.server);
|
||||
everLinked = true;
|
||||
});
|
||||
ws.on('message', onMessage);
|
||||
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 紧接着会来,不重复报
|
||||
}
|
||||
|
||||
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,254 @@
|
||||
#!/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' })); });
|
||||
// 手机/浏览器提前断开:让家里把上游请求也停掉,别白跑
|
||||
req.on('aborted', () => {
|
||||
if (!pending.has(id)) return;
|
||||
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",
|
||||
"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",
|
||||
"main": "src/server.js",
|
||||
"scripts": {
|
||||
|
||||
Reference in New Issue
Block a user