Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
29be7bd9d7 |
@@ -1,53 +0,0 @@
|
|||||||
name: agent-device release
|
|
||||||
|
|
||||||
# 只认设备端标签(agent-device-v0.1.0),不碰主项目的 v2.5.0 这类版本号。
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
tags:
|
|
||||||
- 'agent-device-v*'
|
|
||||||
workflow_dispatch: # 兜底:页面上手动跑,填一个已存在的标签
|
|
||||||
inputs:
|
|
||||||
tag:
|
|
||||||
description: '要发布的标签(已存在),如 agent-device-v0.1.0'
|
|
||||||
required: true
|
|
||||||
|
|
||||||
permissions:
|
|
||||||
contents: write # action-gh-release 需要建 release、传附件
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
release:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- uses: actions/setup-go@v5
|
|
||||||
with:
|
|
||||||
go-version-file: device/go.mod
|
|
||||||
cache-dependency-path: device/go.sum
|
|
||||||
|
|
||||||
# 复用仓库里的脚本,本地和 CI 一套目标列表
|
|
||||||
- name: 编译各平台
|
|
||||||
working-directory: device
|
|
||||||
run: sh scripts/build.sh all
|
|
||||||
|
|
||||||
- name: 发布 Release
|
|
||||||
uses: softprops/action-gh-release@v2
|
|
||||||
with:
|
|
||||||
name: ${{ inputs.tag || github.ref_name }}
|
|
||||||
tag_name: ${{ inputs.tag || github.ref_name }}
|
|
||||||
files: device/bin/agent-device-*
|
|
||||||
fail_on_unmatched_files: true
|
|
||||||
body: |
|
|
||||||
设备执行端 agent-device(`device/`)。
|
|
||||||
|
|
||||||
- 设备主动出站连 core 的 `/dev/ws`,不需要公网 IP、不需要开端口
|
|
||||||
- 二进制不含服务器地址与 token,启动时用 `-server` 或同目录 `config.json` 指定
|
|
||||||
- 模型侧可用 `device` 工具跑命令、看负载、收发文件
|
|
||||||
|
|
||||||
| 平台 | 文件 |
|
|
||||||
| --- | --- |
|
|
||||||
| Linux amd64 / arm64 / mips | `agent-device-linux-*` |
|
|
||||||
| macOS amd64 / arm64 | `agent-device-darwin-*` |
|
|
||||||
| Windows amd64 | `agent-device-windows-amd64.exe` |
|
|
||||||
|
|
||||||
`linux-mips` 是软浮点(`GOMIPS=softfloat`),给 AR9331 这类没 FPU 的 OpenWrt 设备用。
|
|
||||||
+3
-3
@@ -10,6 +10,9 @@ skills/*/.deps_installed
|
|||||||
# 本地端(local/):运行期产物与生成的配置都不入库(含密钥,见 local/README.md)
|
# 本地端(local/):运行期产物与生成的配置都不入库(含密钥,见 local/README.md)
|
||||||
local/.runtime/
|
local/.runtime/
|
||||||
local/config.local.yml
|
local/config.local.yml
|
||||||
|
local/config.win.yml
|
||||||
|
# busybox-w32:Windows 启动器下载的 shell 二进制(不进 git)
|
||||||
|
local/bin/
|
||||||
# officecli 二进制资产:skills/office/install.sh 运行期拉取,不进 git
|
# officecli 二进制资产:skills/office/install.sh 运行期拉取,不进 git
|
||||||
skills/office/bin/
|
skills/office/bin/
|
||||||
skills/**/__pycache__/
|
skills/**/__pycache__/
|
||||||
@@ -22,6 +25,3 @@ app/server/version.json
|
|||||||
# 部署配置真身(含密钥,模板见 scripts/deploy.conf.example);
|
# 部署配置真身(含密钥,模板见 scripts/deploy.conf.example);
|
||||||
deploy.conf
|
deploy.conf
|
||||||
relay/config.json
|
relay/config.json
|
||||||
|
|
||||||
# 设备端编译产物(交叉编译后本地生成,不入库)
|
|
||||||
device/bin/
|
|
||||||
|
|||||||
@@ -10,9 +10,6 @@
|
|||||||
`/chat/completions`)→ 模型调用内置工具 / MCP / 技能 → 命令在 `agent-executor` 隔离容器里执行 →
|
`/chat/completions`)→ 模型调用内置工具 / MCP / 技能 → 命令在 `agent-executor` 隔离容器里执行 →
|
||||||
产物落在会话工作目录并回传。每个会话 = 一个真实 Linux 工作目录 + 一条 SQLite 会话记录。
|
产物落在会话工作目录并回传。每个会话 = 一个真实 Linux 工作目录 + 一条 SQLite 会话记录。
|
||||||
|
|
||||||
另有一个可选的**设备执行端** `device/`:设备主动出站连 core 的 `/dev/ws`,模型用 `device`
|
|
||||||
工具在远端机器(Mac / Windows / OpenWrt 盒子)上跑命令、拉推文件。
|
|
||||||
|
|
||||||
设计基调:**单进程内存模型 + SQLite 同步 API**(JS 单线程,不存在跨进程竞争);**配置冷加载**
|
设计基调:**单进程内存模型 + SQLite 同步 API**(JS 单线程,不存在跨进程竞争);**配置冷加载**
|
||||||
(改 `config.yml` 需重启,少数写盘接口例外);**单租户**(登录只把门,不做资源级授权)。
|
(改 `config.yml` 需重启,少数写盘接口例外);**单租户**(登录只把门,不做资源级授权)。
|
||||||
|
|
||||||
@@ -24,11 +21,10 @@
|
|||||||
| `app/server/` | 后端全部代码(入口 `server.js`) | 见 `app/AGENTS.md` |
|
| `app/server/` | 后端全部代码(入口 `server.js`) | 见 `app/AGENTS.md` |
|
||||||
| `app/server/public/` | 前端静态资源,经典脚本按序加载,共享全局作用域 | 无构建步骤 |
|
| `app/server/public/` | 前端静态资源,经典脚本按序加载,共享全局作用域 | 无构建步骤 |
|
||||||
| `executor/` | **agent-executor**:`/exec` 隔离命令执行 + Office 预览网关 | 零依赖 Node,独立容器 |
|
| `executor/` | **agent-executor**:`/exec` 隔离命令执行 + Office 预览网关 | 零依赖 Node,独立容器 |
|
||||||
| `device/` | **agent-device**:设备执行端,出站连 core 的 `/dev/ws`,提供 exec / 文件传输 | Go 单二进制,交叉编译(amd64/arm64/mips/mipsle/windows),见 `device/README.md` |
|
|
||||||
| `wxbot/` | 微信 iLink 协议调制解调器(多实例) | 独立容器 `agent-wxbot` |
|
| `wxbot/` | 微信 iLink 协议调制解调器(多实例) | 独立容器 `agent-wxbot` |
|
||||||
| `mcp/` | 同栈 MCP 服务:`web_search` / `image_task` / `video_task` / `asr` | 四个容器,仅内网 |
|
| `mcp/` | 同栈 MCP 服务:`web_search` / `image_task` / `video_task` / `asr` | 四个容器,仅内网 |
|
||||||
| `skills/` | 目录式技能(`SKILL.md` + `run.py`/`run.sh`) | 运行时挂载,`skills/deps` 为依赖层 |
|
| `skills/` | 目录式技能(`SKILL.md` + `run.py`/`run.sh`) | 运行时挂载,`skills/deps` 为依赖层 |
|
||||||
| `local/` | **本地端启动器**:同一份代码跑在本机(不起 Docker / executor),`start.sh` 负责探测、装依赖、守护 | 独立于 compose,见 `docs/local-mode.md` |
|
| `local/` | **本地端启动器**:同一份代码跑在本机(不起 Docker / executor)。`start.sh`(macOS/Linux)与 `start-win.mjs`(Windows)负责探测、装依赖、守护 | 独立于 compose,见 `docs/local-mode.md` |
|
||||||
| `tunnel/` | **反向隧道**:服务器端 `server.js` 按 Host / 固定端口 / 通配路由转发,本机 `client.js` 承接 | 独立 compose,见 `tunnel/README.md` |
|
| `tunnel/` | **反向隧道**:服务器端 `server.js` 按 Host / 固定端口 / 通配路由转发,本机 `client.js` 承接 | 独立 compose,见 `tunnel/README.md` |
|
||||||
| `scripts/` | `init.sh` 生成 `.env` + 首次创建 `config.yml`(仅初始管理员);`init_host.sh` 裸机初始化 | 幂等,**不覆盖已有配置** |
|
| `scripts/` | `init.sh` 生成 `.env` + 首次创建 `config.yml`(仅初始管理员);`init_host.sh` 裸机初始化 | 幂等,**不覆盖已有配置** |
|
||||||
| `docs/` | 专题文档:`tool-design.md`(工具接口规范)、`OFFICE.md` | — |
|
| `docs/` | 专题文档:`tool-design.md`(工具接口规范)、`OFFICE.md` | — |
|
||||||
@@ -53,7 +49,6 @@ flowchart TD
|
|||||||
CORE --> EXEC["agent-executor(9000 exec / 3100 预览,仅内网)"]
|
CORE --> EXEC["agent-executor(9000 exec / 3100 预览,仅内网)"]
|
||||||
CORE --> MCP["mcp_web_search / mcp_image_task / mcp_video_task / mcp_asr(3000,仅内网)"]
|
CORE --> MCP["mcp_web_search / mcp_image_task / mcp_video_task / mcp_asr(3000,仅内网)"]
|
||||||
CORE -->|"分段投递回复"| WXBOT
|
CORE -->|"分段投递回复"| WXBOT
|
||||||
DEV["设备:Mac / Windows / OpenWrt"] -->|"wss 出站 /dev/ws"| CORE
|
|
||||||
```
|
```
|
||||||
|
|
||||||
- **对外只暴露 `agent-core` 一个端口**(宿主 `AGENT_PORT`,默认 8090)。executor、wxbot、MCP
|
- **对外只暴露 `agent-core` 一个端口**(宿主 `AGENT_PORT`,默认 8090)。executor、wxbot、MCP
|
||||||
@@ -62,8 +57,6 @@ flowchart TD
|
|||||||
- 容器间按容器名访问(`http://agent-executor:9000`、`http://mcp_web_search:3000/`);
|
- 容器间按容器名访问(`http://agent-executor:9000`、`http://mcp_web_search:3000/`);
|
||||||
所有业务容器同在 `agent-mcp-net`(compose 里固定网络名,避免被加上项目名前缀)。
|
所有业务容器同在 `agent-mcp-net`(compose 里固定网络名,避免被加上项目名前缀)。
|
||||||
- `agent-executor-init` 是一次性容器:把技能依赖装进 `./skills/deps` 后退出,属正常现象。
|
- `agent-executor-init` 是一次性容器:把技能依赖装进 `./skills/deps` 后退出,属正常现象。
|
||||||
- 设备(`device/`)**不需要任何入站端口**:设备主动连 `wss://<PUBLIC_BASE_URL 的 host>/dev/ws`,
|
|
||||||
core 按 `DEVICE_TOKEN` 校验。本地部署没有公网前缀,端点不挂,`device` 工具直接回“未启用”。
|
|
||||||
|
|
||||||
### 端口与网络(要改先看这里)
|
### 端口与网络(要改先看这里)
|
||||||
|
|
||||||
@@ -97,12 +90,12 @@ flowchart TD
|
|||||||
### 环境变量(接线全靠根 `.env` + compose)
|
### 环境变量(接线全靠根 `.env` + compose)
|
||||||
|
|
||||||
`AGENT_CONFIG`、`PORT`、`EXECUTOR_URL`、`EXECUTOR_TOKEN`、`WXBOT_URL`、`WXBOT_TOKEN`、
|
`AGENT_CONFIG`、`PORT`、`EXECUTOR_URL`、`EXECUTOR_TOKEN`、`WXBOT_URL`、`WXBOT_TOKEN`、
|
||||||
`PUBLIC_BASE_URL`、`DEVICE_TOKEN`、`ASR_URL`、`PREVIEW_PROXIES`、`EXECUTOR_LOG_LEVEL`、`WXBOT_LOG_LEVEL`、`ASR_LOG_LEVEL`。
|
`PUBLIC_BASE_URL`、`ASR_URL`、`PREVIEW_PROXIES`、`EXECUTOR_LOG_LEVEL`、`WXBOT_LOG_LEVEL`、`ASR_LOG_LEVEL`。
|
||||||
密钥生成:`./scripts/init.sh`(幂等,重跑不掉登录态;**从不覆盖已有 config.yml**,只在其缺失时创建
|
密钥生成:`./scripts/init.sh`(幂等,重跑不掉登录态;**从不覆盖已有 config.yml**,只在其缺失时创建
|
||||||
最小骨架)。语音识别的上游 key/base/model 不在 env,
|
最小骨架)。语音识别的上游 key/base/model 不在 env,
|
||||||
写在 `config.yml` 的 `mcp_servers[name=asr].headers`(容器不存平台密钥)。
|
写在 `config.yml` 的 `mcp_servers[name=asr].headers`(容器不存平台密钥)。
|
||||||
|
|
||||||
## 四条主链路
|
## 三条主链路
|
||||||
|
|
||||||
1. **Web / HTTP**:`app/server/server.js` 装配 → 路由 → `engine.js` 起回合 →
|
1. **Web / HTTP**:`app/server/server.js` 装配 → 路由 → `engine.js` 起回合 →
|
||||||
`llm.js` 组装并流式调用上游 → `tools/executor.js` 执行工具(`terminal` / `skill` 走
|
`llm.js` 组装并流式调用上游 → `tools/executor.js` 执行工具(`terminal` / `skill` 走
|
||||||
@@ -110,10 +103,7 @@ flowchart TD
|
|||||||
2. **微信**:`agent-wxbot` 收消息 → 回调 core `/wxhook/inbox` → `wechat.js` 落媒体、注入上下文 →
|
2. **微信**:`agent-wxbot` 收消息 → 回调 core `/wxhook/inbox` → `wechat.js` 落媒体、注入上下文 →
|
||||||
`routes/channel.js` 的命令层(`/new` `/switch` `/think` …)→ 同一套 `engine`;回合结束由
|
`routes/channel.js` 的命令层(`/new` `/switch` `/think` …)→ 同一套 `engine`;回合结束由
|
||||||
SSE 内部订阅者(`bus.onInternal`)分段推回微信。
|
SSE 内部订阅者(`bus.onInternal`)分段推回微信。
|
||||||
3. **远端设备**:设备上的 `agent-device` 出站连 core `/dev/ws` → `devices.js` 维护连接表 →
|
3. **定时任务**:`scheduler.js` 每 30s tick → 到期则先 `archiveHistory`(历史整体 `archived`,
|
||||||
模型调 `device` 工具(`list` / `health` / `exec` / `pull` / `push`)→ 命令经 WS 下发、输出分片
|
|
||||||
回传;`pull` 落到会话目录后,`read_file` / 技能可直接消费。
|
|
||||||
4. **定时任务**:`scheduler.js` 每 30s tick → 到期则先 `archiveHistory`(历史整体 `archived`,
|
|
||||||
模型等价新会话)→ `engine.postUserMessage` 投递 → 结束后 `wechat.notifyTask` 通知。
|
模型等价新会话)→ `engine.postUserMessage` 投递 → 结束后 `wechat.notifyTask` 通知。
|
||||||
|
|
||||||
## 数据与状态
|
## 数据与状态
|
||||||
@@ -143,9 +133,7 @@ flowchart TD
|
|||||||
「回合中会话数 → 在用会话数 → 最久未用」择优(详见 `app/AGENTS.md`)。
|
「回合中会话数 → 在用会话数 → 最久未用」择优(详见 `app/AGENTS.md`)。
|
||||||
7. **运行时目录不入库**。`tasks/`、`data/`、`skills/deps/`、`wxbot/data/` 已被 gitignore;
|
7. **运行时目录不入库**。`tasks/`、`data/`、`skills/deps/`、`wxbot/data/` 已被 gitignore;
|
||||||
不要把样例任务、数据库、密钥当成源码提交。
|
不要把样例任务、数据库、密钥当成源码提交。
|
||||||
8. **设备是远端 shell**。`device exec` 在设备上就是 `sh -c` / `cmd /c`;`root` 只约束**起始
|
8. **工具 schema 是每轮全量重发的上下文成本**。新增工具前先读 `docs/tool-design.md`:能用已有工具
|
||||||
cwd**,命令里 `cd /etc` 照样能跑。`DEVICE_TOKEN` 泄漏等价于那台机器的 shell 泄漏,按这个等级管理。
|
|
||||||
9. **工具 schema 是每轮全量重发的上下文成本**。新增工具前先读 `docs/tool-design.md`:能用已有工具
|
|
||||||
的 `op` 扩展就不要新开工具。
|
的 `op` 扩展就不要新开工具。
|
||||||
|
|
||||||
## 开发与验证
|
## 开发与验证
|
||||||
@@ -216,8 +204,6 @@ curl -s http://127.0.0.1:8090/api/health
|
|||||||
| 改微信投递 | `app/server/wechat.js`(业务)+ `app/server/routes/wechat.js`(HTTP/鉴权) |
|
| 改微信投递 | `app/server/wechat.js`(业务)+ `app/server/routes/wechat.js`(HTTP/鉴权) |
|
||||||
| 改语音输入 | `app/server/public/js/voice.js`(录音与插入)+ `app/server/routes/asr.js`(代理)+ `mcp/asr/`(转写);客户端桥契约见 `docs/voice-input.md` |
|
| 改语音输入 | `app/server/public/js/voice.js`(录音与插入)+ `app/server/routes/asr.js`(代理)+ `mcp/asr/`(转写);客户端桥契约见 `docs/voice-input.md` |
|
||||||
| 改隔离执行 | `executor/server.js`(先读顶部安全模型注释) |
|
| 改隔离执行 | `executor/server.js`(先读顶部安全模型注释) |
|
||||||
| 改设备执行 / 文件传输 | `app/server/devices.js`(连接表 + exec/health/pull/push)+ `app/server/tools/executor.js` 的 `toolDevice` |
|
|
||||||
| 改设备端行为 | `device/cmd/agent/`(协议 `device/pkg/proto`,连接基座 `device/pkg/wsnode`) |
|
|
||||||
| 改隧道路由 / 转发 | `tunnel/server.js`(按 Host / 端口匹配)+ `tunnel/client.js`(本地服务映射) |
|
| 改隧道路由 / 转发 | `tunnel/server.js`(按 Host / 端口匹配)+ `tunnel/client.js`(本地服务映射) |
|
||||||
| 加同栈 MCP 服务 | `mcp/<name>/` + `docker-compose.yml` + `config.yml` 的 `mcp_servers` |
|
| 加同栈 MCP 服务 | `mcp/<name>/` + `docker-compose.yml` + `config.yml` 的 `mcp_servers` |
|
||||||
| 加技能 | `skills/<name>/`(`SKILL.md` + `run.py`),见 `skills/README.md` |
|
| 加技能 | `skills/<name>/`(`SKILL.md` + `run.py`),见 `skills/README.md` |
|
||||||
|
|||||||
@@ -41,29 +41,6 @@ macOS / Linux,Node 20+,不需要 Docker:
|
|||||||
| [`skills/`](skills/README.md) | 内置技能 |
|
| [`skills/`](skills/README.md) | 内置技能 |
|
||||||
| [`local/`](local/README.md) | 本机模式启动器 |
|
| [`local/`](local/README.md) | 本机模式启动器 |
|
||||||
| [`tunnel/`](tunnel/README.md) | 反向隧道:把本机服务经服务器中转,供外网访问 |
|
| [`tunnel/`](tunnel/README.md) | 反向隧道:把本机服务经服务器中转,供外网访问 |
|
||||||
| [`device/`](device/README.md) | 设备执行端:任意机器装上就连回来,模型可在上面跑命令、传文件 |
|
|
||||||
|
|
||||||
## 远端设备
|
|
||||||
|
|
||||||
把任意一台机器(Mac / Linux / Windows / OpenWrt 盒子)接进来,让模型在它上面执行命令、读写文件:
|
|
||||||
|
|
||||||
1. 编译或下载 `device/` 的二进制,和 `config.json` 放在同一个目录:
|
|
||||||
|
|
||||||
```json
|
|
||||||
{ "server": "wss://你的域名/dev/ws", "token": "<DEVICE_TOKEN>", "root": "/Users/you", "name": "mac-01" }
|
|
||||||
```
|
|
||||||
|
|
||||||
2. 直接运行(默认读同目录的 `config.json`,token 不会出现在 `ps` 里):
|
|
||||||
|
|
||||||
```bash
|
|
||||||
./agent-device-darwin-amd64
|
|
||||||
```
|
|
||||||
|
|
||||||
3. 服务器 `.env` 里配同一个 `DEVICE_TOKEN` 并重启 core。
|
|
||||||
|
|
||||||
设备**主动出站**连接,不需要公网 IP、不需要开端口。连上后模型侧多出 `device` 工具:
|
|
||||||
`list` 看在线设备、`health` 看负载、`exec` 跑命令、`pull`/`push` 收发文件(单个 2 GiB 以内)。
|
|
||||||
盒子上的常驻用系统自带的服务管理器(systemd / procd / schtasks),细节见 [`device/README.md`](device/README.md)。
|
|
||||||
|
|
||||||
## 配置
|
## 配置
|
||||||
|
|
||||||
|
|||||||
@@ -59,6 +59,7 @@ AGENT_CONFIG=./config.yml node server/server.js
|
|||||||
| `server/public-files.js` | `mint_public_link` 的短链签发与解析(进程内 Map) |
|
| `server/public-files.js` | `mint_public_link` 的短链签发与解析(进程内 Map) |
|
||||||
| `server/download-token.js` | 浏览器下载链接的 HMAC 签名(密钥进程内随机) |
|
| `server/download-token.js` | 浏览器下载链接的 HMAC 签名(密钥进程内随机) |
|
||||||
| `server/remote-exec.js` | 调 `agent-executor` 的 `/exec`(SSE)与预览槽清理 |
|
| `server/remote-exec.js` | 调 `agent-executor` 的 `/exec`(SSE)与预览槽清理 |
|
||||||
|
| `server/shell.js` | **执行后端**:解析用哪个 POSIX shell 跑命令(POSIX 直接 `/bin/sh`;Windows 依次 git-bash → busybox-w32)、跨平台杀进程树。平台差异只允许出现在这里 |
|
||||||
| `server/log.js` | 分级日志 `log.debug/info/warn/error(category, ...)` |
|
| `server/log.js` | 分级日志 `log.debug/info/warn/error(category, ...)` |
|
||||||
| `server/balance.js` | 平台余额查询适配器(按 `platform.type` 分发) |
|
| `server/balance.js` | 平台余额查询适配器(按 `platform.type` 分发) |
|
||||||
| `server/version.js` | git commit/date:优先读 `version.json`(post-commit 钩子生成),宿主机有 git 时兜底 `git rev-parse`;页面版本号另外由 `routes/system.js` 的 `VERSION` 字面量决定 |
|
| `server/version.js` | git commit/date:优先读 `version.json`(post-commit 钩子生成),宿主机有 git 时兜底 `git rev-parse`;页面版本号另外由 `routes/system.js` 的 `VERSION` 字面量决定 |
|
||||||
@@ -403,6 +404,9 @@ preview-proxy.mount(末尾兜底)
|
|||||||
|
|
||||||
## 陷阱清单(都是踩过的)
|
## 陷阱清单(都是踩过的)
|
||||||
|
|
||||||
|
- **平台差异只允许出现在 `server/shell.js`**:`terminal` / 技能 / `engine.killRunProcs` 一律走
|
||||||
|
`shell.spawnShell` / `shell.killTree`,上层不写 `process.platform` 分支。POSIX 分支的行为
|
||||||
|
(`/bin/sh -c` + 进程组 + `kill(-pid)`)不能变——它是「模型按 POSIX 写就一定能跑」的保证。
|
||||||
- **循环依赖**:`engine` 绝不 `require('./wechat')` 或 `require('./scheduler')`,否则拿到半成品
|
- **循环依赖**:`engine` 绝不 `require('./wechat')` 或 `require('./scheduler')`,否则拿到半成品
|
||||||
exports。通知面/engine 引用一律由 `server.js` 注入。`executor → scheduler` 是单向的,安全。
|
exports。通知面/engine 引用一律由 `server.js` 注入。`executor → scheduler` 是单向的,安全。
|
||||||
- **tool_call 配对**:删 assistant 必须连带删该轮的 `tool` 回执;删单条 `tool` 回执必须从父
|
- **tool_call 配对**:删 assistant 必须连带删该轮的 `tool` 回执;删单条 `tool` 回执必须从父
|
||||||
|
|||||||
@@ -33,6 +33,9 @@ log_level: "info" # debug < info < warn < error
|
|||||||
terminal:
|
terminal:
|
||||||
default_timeout_ms: 30000 # 命令默认超时(ms)
|
default_timeout_ms: 30000 # 命令默认超时(ms)
|
||||||
max_output_chars: 10000 # 回传模型的最大输出字符数
|
max_output_chars: 10000 # 回传模型的最大输出字符数
|
||||||
|
# shell: '' # 跑命令的 POSIX shell;空 = 自动探测
|
||||||
|
# POSIX:/bin/sh;Windows:git-bash → busybox-w32
|
||||||
|
# env AGENT_SHELL 优先级更高,AGENT_SHELL_ARGS 可改参数模板
|
||||||
|
|
||||||
fetch:
|
fetch:
|
||||||
timeout_ms: 30000 # 抓取总超时(ms),覆盖响应头到 body 读完
|
timeout_ms: 30000 # 抓取总超时(ms),覆盖响应头到 body 读完
|
||||||
|
|||||||
Generated
-22
@@ -14,7 +14,6 @@
|
|||||||
"multer": "1.4.5-lts.1",
|
"multer": "1.4.5-lts.1",
|
||||||
"sharp": "0.35.4",
|
"sharp": "0.35.4",
|
||||||
"turndown": "7.2.0",
|
"turndown": "7.2.0",
|
||||||
"ws": "^8.23.0",
|
|
||||||
"yaml": "2.6.1"
|
"yaml": "2.6.1"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -2003,27 +2002,6 @@
|
|||||||
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
|
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
|
||||||
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="
|
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="
|
||||||
},
|
},
|
||||||
"node_modules/ws": {
|
|
||||||
"version": "8.23.0",
|
|
||||||
"resolved": "https://registry.npmmirror.com/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/xtend": {
|
"node_modules/xtend": {
|
||||||
"version": "4.0.2",
|
"version": "4.0.2",
|
||||||
"resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",
|
"resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",
|
||||||
|
|||||||
@@ -13,7 +13,6 @@
|
|||||||
"multer": "1.4.5-lts.1",
|
"multer": "1.4.5-lts.1",
|
||||||
"sharp": "0.35.4",
|
"sharp": "0.35.4",
|
||||||
"turndown": "7.2.0",
|
"turndown": "7.2.0",
|
||||||
"ws": "^8.23.0",
|
|
||||||
"yaml": "2.6.1"
|
"yaml": "2.6.1"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -76,7 +76,9 @@ const DEFAULTS = {
|
|||||||
db_path: '',
|
db_path: '',
|
||||||
// executor / 微信接入(wxbot)均不占配置字段:两组件接线纯 env(compose 经根 .env 注入,见 parseAndValidate);
|
// executor / 微信接入(wxbot)均不占配置字段:两组件接线纯 env(compose 经根 .env 注入,见 parseAndValidate);
|
||||||
// 本配置文件内含密钥,只给 core 进程读,executor/wxbot 一律不挂不读。
|
// 本配置文件内含密钥,只给 core 进程读,executor/wxbot 一律不挂不读。
|
||||||
terminal: { default_timeout_ms: 30000, max_output_chars: 10000 },
|
// terminal.shell:跑命令用的 POSIX shell(空 = 自动探测:POSIX 直接 /bin/sh;Windows 依次找
|
||||||
|
// git-bash、busybox-w32)。env AGENT_SHELL 优先级更高,AGENT_SHELL_ARGS 覆盖参数模板(默认 -c)。
|
||||||
|
terminal: { default_timeout_ms: 30000, max_output_chars: 10000, shell: '' },
|
||||||
// fetch:timeout_ms 覆盖请求发出到 body 读完的全生命周期;max_bytes 为流式抓取字节上限(超限即断开)。
|
// fetch:timeout_ms 覆盖请求发出到 body 读完的全生命周期;max_bytes 为流式抓取字节上限(超限即断开)。
|
||||||
// 下载与返回两上限解耦:下载不进上下文可宽松,返回默认收紧(max_chars),模型显式传 max_chars 时
|
// 下载与返回两上限解耦:下载不进上下文可宽松,返回默认收紧(max_chars),模型显式传 max_chars 时
|
||||||
// 夹在 max_chars_hard 硬帽内;超窗尾部提示 offset,续读走 ctx.run 上的回合缓存不重抓。
|
// 夹在 max_chars_hard 硬帽内;超窗尾部提示 offset,续读走 ctx.run 上的回合缓存不重抓。
|
||||||
|
|||||||
@@ -1,448 +0,0 @@
|
|||||||
// 设备(远端执行节点)接入层。
|
|
||||||
//
|
|
||||||
// 设备主动出站连 wss://<公网前缀>/dev/ws,core 维护连接表;工具调用时把命令推下去、
|
|
||||||
// 把 stdout/stderr/退出码收回来。设备侧不需要任何入站端口,所以家里的盒子、公司的
|
|
||||||
// Windows 都能直接在 NAT 后面接进来。
|
|
||||||
//
|
|
||||||
// 启用条件:有公网前缀(config.yml public_link.base_url 或 env PUBLIC_BASE_URL)
|
|
||||||
// 且配了 DEVICE_TOKEN。本地部署两者都没有,设备也连不进来,端点干脆不挂。
|
|
||||||
const crypto = require('crypto');
|
|
||||||
const fs = require('fs');
|
|
||||||
const WebSocket = require('ws');
|
|
||||||
const log = require('./log');
|
|
||||||
|
|
||||||
const PATH = '/dev/ws';
|
|
||||||
const PING_MS = 20000; // nginx 默认 60s 空闲断,20s 足够安全
|
|
||||||
const DEAD_SEC = 61; // 超过这么久没任何消息 → 判假死
|
|
||||||
const HELLO_MS = 10000; // 连上后多久没 hello 就踢
|
|
||||||
const DEFAULT_TIMEOUT_MS = 120000;
|
|
||||||
const MAX_TIMEOUT_MS = 600000;
|
|
||||||
const MAX_OUT_CHARS = 256 * 1024; // 单流回传上限,超出截断(免得一次把上下文塞爆)
|
|
||||||
|
|
||||||
const state = {
|
|
||||||
enabled: false,
|
|
||||||
token: '',
|
|
||||||
wss: null,
|
|
||||||
byName: new Map(), // name -> device
|
|
||||||
pending: new Map(), // 请求 id -> { onChunk, onExit, onHealth }
|
|
||||||
};
|
|
||||||
|
|
||||||
function init(cfg) {
|
|
||||||
const base = String((cfg.public_link && cfg.public_link.base_url) || '').trim();
|
|
||||||
state.token = String(process.env.DEVICE_TOKEN || '').trim();
|
|
||||||
state.enabled = !!(base && state.token);
|
|
||||||
if (state.enabled) {
|
|
||||||
let host = base;
|
|
||||||
try { host = new URL(base).host; } catch (_) { /* 保留原文 */ }
|
|
||||||
log.info('devices', '设备接入已启用:wss://' + host + PATH);
|
|
||||||
} else {
|
|
||||||
log.info('devices', '设备接入未启用(' + (base ? '缺 DEVICE_TOKEN' : '无公网前缀') + ')');
|
|
||||||
}
|
|
||||||
return state.enabled;
|
|
||||||
}
|
|
||||||
|
|
||||||
function enabled() {
|
|
||||||
return state.enabled;
|
|
||||||
}
|
|
||||||
|
|
||||||
function tokenOK(given) {
|
|
||||||
if (!state.token) return false;
|
|
||||||
const a = Buffer.from(String(given || ''));
|
|
||||||
const b = Buffer.from(state.token);
|
|
||||||
return a.length === b.length && crypto.timingSafeEqual(a, b);
|
|
||||||
}
|
|
||||||
|
|
||||||
function attach(server) {
|
|
||||||
if (!state.enabled) return;
|
|
||||||
state.wss = new WebSocket.Server({ noServer: true, maxPayload: 8 * 1024 * 1024 });
|
|
||||||
server.on('upgrade', (req, socket, head) => {
|
|
||||||
let url;
|
|
||||||
try { url = new URL(req.url, 'http://x'); } catch (_) { return; }
|
|
||||||
if (url.pathname !== PATH) return; // 不认识的 upgrade 不归这层管
|
|
||||||
const hdr = String(req.headers.authorization || '');
|
|
||||||
const bearer = hdr.toLowerCase().startsWith('bearer ') ? hdr.slice(7).trim() : '';
|
|
||||||
if (!tokenOK(bearer || url.searchParams.get('token'))) {
|
|
||||||
log.warn('devices', '设备接入被拒:token 不匹配(来自 ' + (req.socket.remoteAddress || '?') + ')');
|
|
||||||
socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
|
|
||||||
socket.destroy();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
state.wss.handleUpgrade(req, socket, head, ws => state.wss.emit('connection', ws, req));
|
|
||||||
});
|
|
||||||
state.wss.on('connection', onConnection);
|
|
||||||
setInterval(() => {
|
|
||||||
const now = Date.now();
|
|
||||||
for (const dev of state.byName.values()) {
|
|
||||||
if (now - dev.lastSeen > DEAD_SEC * 1000) {
|
|
||||||
log.warn('devices', '设备无消息超时,断开:' + dev.name);
|
|
||||||
try { dev.ws.terminate(); } catch (_) {}
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
try { dev.ws.send(JSON.stringify({ t: 'ping' })); } catch (_) {}
|
|
||||||
}
|
|
||||||
}, PING_MS).unref();
|
|
||||||
}
|
|
||||||
|
|
||||||
function onConnection(ws) {
|
|
||||||
const dev = {
|
|
||||||
ws, name: null, os: '', arch: '', shell: '', shellPath: '', shellVer: '', root: '', ver: '',
|
|
||||||
connectedAt: Date.now(), lastSeen: Date.now(), helloTimer: null,
|
|
||||||
};
|
|
||||||
dev.helloTimer = setTimeout(() => {
|
|
||||||
if (!dev.name) { try { ws.close(4001, 'hello timeout'); } catch (_) {} }
|
|
||||||
}, HELLO_MS);
|
|
||||||
|
|
||||||
ws.on('message', raw => {
|
|
||||||
let m;
|
|
||||||
try { m = JSON.parse(String(raw)); } catch (_) { return; }
|
|
||||||
dev.lastSeen = Date.now();
|
|
||||||
if (m.t === 'hello') return onHello(dev, m);
|
|
||||||
if (m.t === 'chunk') {
|
|
||||||
const p = state.pending.get(m.id);
|
|
||||||
if (p && p.onChunk) p.onChunk(m);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (m.t === 'exit') {
|
|
||||||
const p = state.pending.get(m.id);
|
|
||||||
if (p && p.onExit) p.onExit(m);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (m.t === 'file.chunk') {
|
|
||||||
const p = state.pending.get(m.id);
|
|
||||||
if (p && p.onFileChunk) p.onFileChunk(m);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (m.t === 'file.done') {
|
|
||||||
const p = state.pending.get(m.id);
|
|
||||||
if (p && p.onFileDone) p.onFileDone(m);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (m.t === 'health') {
|
|
||||||
const p = state.pending.get(m.id);
|
|
||||||
if (p && p.onHealth) p.onHealth(m);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
ws.on('close', () => {
|
|
||||||
clearTimeout(dev.helloTimer);
|
|
||||||
if (dev.name && state.byName.get(dev.name) === dev) {
|
|
||||||
state.byName.delete(dev.name);
|
|
||||||
log.info('devices', '设备下线:' + dev.name);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
ws.on('error', () => {});
|
|
||||||
}
|
|
||||||
|
|
||||||
function onHello(dev, m) {
|
|
||||||
clearTimeout(dev.helloTimer);
|
|
||||||
dev.name = String(m.name || '').trim() || ('dev-' + crypto.randomBytes(3).toString('hex'));
|
|
||||||
dev.os = String(m.os || '');
|
|
||||||
dev.arch = String(m.arch || '');
|
|
||||||
dev.shell = String(m.shell || '');
|
|
||||||
dev.shellPath = String(m.shell_path || '');
|
|
||||||
dev.shellVer = String(m.shell_ver || '');
|
|
||||||
dev.root = String(m.root || '');
|
|
||||||
dev.ver = String(m.ver || '');
|
|
||||||
|
|
||||||
const old = state.byName.get(dev.name);
|
|
||||||
if (old && old !== dev) {
|
|
||||||
log.warn('devices', '同名设备重新接入,踢掉旧连接:' + dev.name);
|
|
||||||
try { old.ws.close(4000, 'replaced'); } catch (_) {}
|
|
||||||
}
|
|
||||||
state.byName.set(dev.name, dev);
|
|
||||||
log.info('devices', `设备上线:${dev.name}(${dev.os}/${dev.arch} shell=${dev.shellPath || dev.shell} ${dev.shellVer} root=${dev.root})`);
|
|
||||||
}
|
|
||||||
|
|
||||||
function pick(name) {
|
|
||||||
if (name) return state.byName.get(String(name).trim()) || null;
|
|
||||||
const first = state.byName.values().next();
|
|
||||||
return first.done ? null : first.value;
|
|
||||||
}
|
|
||||||
|
|
||||||
function list() {
|
|
||||||
const now = Date.now();
|
|
||||||
return [...state.byName.values()].map(d => ({
|
|
||||||
device: d.name,
|
|
||||||
os: d.os,
|
|
||||||
arch: d.arch,
|
|
||||||
// shell 是模型的命令入口:kind 决定调用形式(sh -c / cmd /c),path 决定实际解释器
|
|
||||||
//(/bin/sh 可能是 dash、bash 或 busybox),ver 拿得到就给。
|
|
||||||
shell: d.shell,
|
|
||||||
shell_path: d.shellPath,
|
|
||||||
shell_ver: d.shellVer,
|
|
||||||
root: d.root,
|
|
||||||
ver: d.ver,
|
|
||||||
connected_sec: Math.round((now - d.connectedAt) / 1000),
|
|
||||||
idle_sec: Math.round((now - d.lastSeen) / 1000),
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
function health(name) {
|
|
||||||
const dev = pick(name);
|
|
||||||
if (!dev) return Promise.reject(new Error(name ? `设备 ${name} 不在线` : '当前没有设备在线'));
|
|
||||||
const id = newJobId();
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
const timer = setTimeout(() => {
|
|
||||||
state.pending.delete(id);
|
|
||||||
reject(new Error(`设备 ${dev.name} 未在 5s 内回应 health`));
|
|
||||||
}, 5000);
|
|
||||||
state.pending.set(id, {
|
|
||||||
onHealth(m) {
|
|
||||||
clearTimeout(timer);
|
|
||||||
state.pending.delete(id);
|
|
||||||
resolve({
|
|
||||||
device: dev.name, os: dev.os, arch: dev.arch,
|
|
||||||
uptime_sec: m.uptime_sec, host_uptime_sec: m.host_uptime_sec,
|
|
||||||
load1: m.load1, load5: m.load5, load15: m.load15,
|
|
||||||
mem_total_mb: m.mem_total_mb, mem_free_mb: m.mem_free_mb,
|
|
||||||
disk_total_gb: m.disk_total_gb, disk_free_gb: m.disk_free_gb, temp_c: m.temp_c,
|
|
||||||
});
|
|
||||||
},
|
|
||||||
});
|
|
||||||
try {
|
|
||||||
dev.ws.send(JSON.stringify({ t: 'health', id }));
|
|
||||||
} catch (e) {
|
|
||||||
clearTimeout(timer);
|
|
||||||
state.pending.delete(id);
|
|
||||||
reject(new Error('下发 health 失败:' + e.message));
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function newJobId() {
|
|
||||||
return crypto.randomBytes(6).toString('hex');
|
|
||||||
}
|
|
||||||
|
|
||||||
function exec({ device, command, cwd, timeout_ms }) {
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
const dev = pick(device);
|
|
||||||
if (!dev) return reject(new Error(device ? `设备 ${device} 不在线` : '当前没有设备在线'));
|
|
||||||
const cmd = String(command || '');
|
|
||||||
if (!cmd.trim()) return reject(new Error('command 不能为空'));
|
|
||||||
const tmo = Math.min(Math.max(Number(timeout_ms) || DEFAULT_TIMEOUT_MS, 1000), MAX_TIMEOUT_MS);
|
|
||||||
const id = newJobId();
|
|
||||||
const started = Date.now();
|
|
||||||
let out = '';
|
|
||||||
let err = '';
|
|
||||||
let truncated = false;
|
|
||||||
let settled = false;
|
|
||||||
|
|
||||||
const done = payload => {
|
|
||||||
if (settled) return;
|
|
||||||
settled = true;
|
|
||||||
clearTimeout(watchdog);
|
|
||||||
state.pending.delete(id);
|
|
||||||
resolve(payload);
|
|
||||||
};
|
|
||||||
|
|
||||||
// 兜底看门狗:设备侧本来就会按 timeout 杀进程,这里再晚 10s 收尸,防止设备掉线后永远挂着
|
|
||||||
const watchdog = setTimeout(() => {
|
|
||||||
done({
|
|
||||||
device: dev.name, code: -1, killed_by: 'watchdog', ms: Date.now() - started,
|
|
||||||
stdout: out, stderr: err, truncated,
|
|
||||||
note: '设备未在超时后回传结果(可能已掉线)',
|
|
||||||
});
|
|
||||||
}, tmo + 10000);
|
|
||||||
|
|
||||||
state.pending.set(id, {
|
|
||||||
onChunk(m) {
|
|
||||||
const text = Buffer.from(String(m.chunk || ''), 'base64').toString('utf8');
|
|
||||||
if (m.out === 'err') {
|
|
||||||
if (err.length + text.length > MAX_OUT_CHARS) { truncated = true; err += text.slice(0, Math.max(0, MAX_OUT_CHARS - err.length)); }
|
|
||||||
else err += text;
|
|
||||||
} else {
|
|
||||||
if (out.length + text.length > MAX_OUT_CHARS) { truncated = true; out += text.slice(0, Math.max(0, MAX_OUT_CHARS - out.length)); }
|
|
||||||
else out += text;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
onExit(m) {
|
|
||||||
done({
|
|
||||||
device: dev.name,
|
|
||||||
code: typeof m.code === 'number' ? m.code : -1,
|
|
||||||
killed_by: m.killed_by || '',
|
|
||||||
ms: Number(m.ms) || Date.now() - started,
|
|
||||||
stdout: out,
|
|
||||||
stderr: err + (m.err ? String(m.err) : ''),
|
|
||||||
truncated: truncated || !!m.truncated,
|
|
||||||
});
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
try {
|
|
||||||
dev.ws.send(JSON.stringify({
|
|
||||||
t: 'exec', id, cmd, cwd: cwd ? String(cwd) : '', timeout_ms: tmo,
|
|
||||||
}));
|
|
||||||
} catch (e) {
|
|
||||||
state.pending.delete(id);
|
|
||||||
clearTimeout(watchdog);
|
|
||||||
reject(new Error('下发命令失败:' + e.message));
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// ---------- 文件通道 ----------
|
|
||||||
// core 与设备之间拉/推单个文件,复用同一条 WS:256 KiB 一块,base64 传输。
|
|
||||||
// 写盘一律先落 .part,size 与 sha256 都对上才 rename——不留半截文件。
|
|
||||||
const FILE_CHUNK = 256 * 1024; // 每块 256 KiB
|
|
||||||
const MAX_FILE = 2 * 1024 * 1024 * 1024; // 单文件上限 2 GiB
|
|
||||||
const FIRST_CHUNK_MS = 30000; // 请求发出后等第一块(覆盖设备端 open/stat)
|
|
||||||
const IDLE_MS = 30000; // 块与块之间的空闲超时:只看卡不卡,不看总共多久
|
|
||||||
const DONE_WAIT_MS = 60000; // push 发完最后一包后等设备确认
|
|
||||||
const WS_HIGH = 4 * 1024 * 1024; // 发送缓冲高水位,超了就歇一会
|
|
||||||
|
|
||||||
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
|
||||||
|
|
||||||
// 流式算 sha256:2 GiB 不能整块读进内存
|
|
||||||
function hashFile(p) {
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
const h = crypto.createHash('sha256');
|
|
||||||
fs.createReadStream(p)
|
|
||||||
.on('data', c => h.update(c))
|
|
||||||
.on('end', () => resolve(h.digest('hex')))
|
|
||||||
.on('error', reject);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// pull:设备 → 会话目录
|
|
||||||
// 超时按「空闲」算:首块 30s,之后每收到一块重置 30s。稳定但慢的链路不会被误杀。
|
|
||||||
function pull({ device, remotePath, localPath }) {
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
const dev = pick(device);
|
|
||||||
if (!dev) return reject(new Error(device ? `设备 ${device} 不在线` : '当前没有设备在线'));
|
|
||||||
if (!remotePath) return reject(new Error('remote_path 不能为空'));
|
|
||||||
|
|
||||||
const id = newJobId();
|
|
||||||
const tmp = localPath + '.part';
|
|
||||||
const out = fs.createWriteStream(tmp);
|
|
||||||
const hash = crypto.createHash('sha256');
|
|
||||||
let got = 0;
|
|
||||||
let settled = false;
|
|
||||||
let paused = false;
|
|
||||||
let idle = null;
|
|
||||||
|
|
||||||
const finish = () => {
|
|
||||||
if (settled) return false;
|
|
||||||
settled = true;
|
|
||||||
clearTimeout(idle);
|
|
||||||
state.pending.delete(id);
|
|
||||||
// 背压可能把连接停在 pause 上:结束时必须恢复,否则后续所有消息都收不到
|
|
||||||
if (paused) {
|
|
||||||
paused = false;
|
|
||||||
try { dev.ws.resume(); } catch (_) {}
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
};
|
|
||||||
const fail = msg => {
|
|
||||||
if (!finish()) return;
|
|
||||||
try { out.destroy(); } catch (_) {}
|
|
||||||
try { fs.unlinkSync(tmp); } catch (_) {}
|
|
||||||
reject(new Error(msg));
|
|
||||||
};
|
|
||||||
const bump = ms => {
|
|
||||||
clearTimeout(idle);
|
|
||||||
idle = setTimeout(() => fail(`${ms / 1000}s 没有收到数据,判定卡住`), ms);
|
|
||||||
};
|
|
||||||
bump(FIRST_CHUNK_MS);
|
|
||||||
|
|
||||||
state.pending.set(id, {
|
|
||||||
onFileChunk(m) {
|
|
||||||
if (settled) return;
|
|
||||||
bump(IDLE_MS);
|
|
||||||
let b;
|
|
||||||
try { b = Buffer.from(String(m.data || ''), 'base64'); } catch (_) { return fail('数据块解码失败'); }
|
|
||||||
got += b.length;
|
|
||||||
if (got > MAX_FILE) return fail('文件超过 2GiB 上限');
|
|
||||||
hash.update(b);
|
|
||||||
// 磁盘比网络慢时暂停从连接读,等 drain 再恢复——否则缓冲会在内存里堆到 OOM
|
|
||||||
if (!out.write(b) && !paused) {
|
|
||||||
paused = true;
|
|
||||||
try { dev.ws.pause(); } catch (_) {}
|
|
||||||
out.once('drain', () => {
|
|
||||||
paused = false;
|
|
||||||
try { dev.ws.resume(); } catch (_) {}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
},
|
|
||||||
onFileDone(m) {
|
|
||||||
if (settled) return;
|
|
||||||
clearTimeout(idle);
|
|
||||||
if (m.err) return fail(String(m.err));
|
|
||||||
out.end(() => {
|
|
||||||
if (!finish()) return;
|
|
||||||
const sum = hash.digest('hex');
|
|
||||||
if (typeof m.size === 'number' && m.size !== got) {
|
|
||||||
try { fs.unlinkSync(tmp); } catch (_) {}
|
|
||||||
return reject(new Error(`大小不符:收到 ${got},设备报 ${m.size}`));
|
|
||||||
}
|
|
||||||
if (m.sha256 && String(m.sha256).toLowerCase() !== sum) {
|
|
||||||
try { fs.unlinkSync(tmp); } catch (_) {}
|
|
||||||
return reject(new Error('sha256 不符'));
|
|
||||||
}
|
|
||||||
try { fs.renameSync(tmp, localPath); } catch (e) { return reject(e); }
|
|
||||||
resolve({ device: dev.name, bytes: got, sha256: sum, path: localPath });
|
|
||||||
});
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
dev.ws.send(JSON.stringify({ t: 'file', id, op: 'read', path: remotePath }));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// push:会话目录 → 设备
|
|
||||||
// 发送阶段不设总超时(core 自己知道在发,靠 bufferedAmount 控节奏),
|
|
||||||
// 发完最后一包才开始等设备确认(60s)。
|
|
||||||
async function push({ device, localPath, remotePath }) {
|
|
||||||
const dev = pick(device);
|
|
||||||
if (!dev) throw new Error(device ? `设备 ${device} 不在线` : '当前没有设备在线');
|
|
||||||
if (!remotePath) throw new Error('remote_path 不能为空');
|
|
||||||
|
|
||||||
const st = fs.statSync(localPath);
|
|
||||||
if (!st.isFile()) throw new Error('只能推文件,不能推目录:' + localPath);
|
|
||||||
if (st.size > MAX_FILE) throw new Error('文件超过 2GiB 上限');
|
|
||||||
const size = st.size;
|
|
||||||
const sum = await hashFile(localPath);
|
|
||||||
const id = newJobId();
|
|
||||||
|
|
||||||
let settled = false;
|
|
||||||
let doneTimer = null;
|
|
||||||
let rejectDone = null;
|
|
||||||
const done = new Promise((resolve, reject) => {
|
|
||||||
rejectDone = reject;
|
|
||||||
state.pending.set(id, {
|
|
||||||
onFileDone(m) {
|
|
||||||
if (settled) return;
|
|
||||||
settled = true;
|
|
||||||
clearTimeout(doneTimer);
|
|
||||||
state.pending.delete(id);
|
|
||||||
if (m.err) return reject(new Error(String(m.err)));
|
|
||||||
resolve({ device: dev.name, bytes: size, sha256: sum, path: remotePath });
|
|
||||||
},
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
try {
|
|
||||||
dev.ws.send(JSON.stringify({ t: 'file', id, op: 'write', path: remotePath, size, sha256: sum }));
|
|
||||||
for await (const chunk of fs.createReadStream(localPath, { highWaterMark: FILE_CHUNK })) {
|
|
||||||
dev.ws.send(JSON.stringify({ t: 'file.chunk', id, data: chunk.toString('base64') }));
|
|
||||||
while (dev.ws.bufferedAmount > WS_HIGH) await sleep(10);
|
|
||||||
}
|
|
||||||
dev.ws.send(JSON.stringify({ t: 'file.done', id }));
|
|
||||||
} catch (e) {
|
|
||||||
settled = true;
|
|
||||||
state.pending.delete(id);
|
|
||||||
throw e;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 发完最后一包才开始看门狗:设备还要算 sha、rename,慢盘上会停几秒
|
|
||||||
doneTimer = setTimeout(() => {
|
|
||||||
if (settled) return;
|
|
||||||
settled = true;
|
|
||||||
state.pending.delete(id);
|
|
||||||
rejectDone(new Error(`发完最后一包后 ${DONE_WAIT_MS / 1000}s 仍未收到设备确认`));
|
|
||||||
}, DONE_WAIT_MS);
|
|
||||||
|
|
||||||
return done;
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = { init, attach, enabled, list, health, exec, pull, push, PATH };
|
|
||||||
+12
-42
@@ -8,6 +8,7 @@ const { executeTool, resolveInTask } = require('./tools/executor');
|
|||||||
const publicFiles = require('./public-files');
|
const publicFiles = require('./public-files');
|
||||||
const mcp = require('./mcp');
|
const mcp = require('./mcp');
|
||||||
const rexec = require('./remote-exec');
|
const rexec = require('./remote-exec');
|
||||||
|
const shell = require('./shell'); // 执行后端:killTree 的平台差异(进程组 / taskkill)不往引擎里渗
|
||||||
const log = require('./log');
|
const log = require('./log');
|
||||||
const profile = require('./user-profile');
|
const profile = require('./user-profile');
|
||||||
const memory = require('./memory');
|
const memory = require('./memory');
|
||||||
@@ -118,19 +119,11 @@ function archivedCount(history) {
|
|||||||
return n;
|
return n;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 同上,但按 sessionId 现查:编辑/删除入口拿到的是裸 sessions 行(不含 history),
|
|
||||||
// 用 archivedCount(session.history) 会恒得 0,作废的 cid 就打到别的 key 上(压缩过的会话必踩)。
|
|
||||||
function archivedCountOf(sessionId) {
|
|
||||||
const r = db.prepare("SELECT COUNT(*) AS n FROM messages WHERE session_id = ? AND type = 'archived'").get(sessionId);
|
|
||||||
return r ? r.n : 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 增量上下文 id 的拼法(与 llm.js 的 X-Context-Id 一致):<core_id>:<user>:<session_id>:<archived_cnt>。
|
// 增量上下文 id 的拼法(与 llm.js 的 X-Context-Id 一致):<core_id>:<user>:<session_id>:<archived_cnt>。
|
||||||
// 删除消息后要把这个 key 作废,让下一轮走全量重建。
|
// 删除消息后要把这个 key 作废,让下一轮走全量重建。
|
||||||
// runLoop 里 session.history 已就绪,走内存计数;其余入口现查库,两条路结果一致。
|
|
||||||
function contextIdOf(session) {
|
function contextIdOf(session) {
|
||||||
const n = session.history ? archivedCount(session.history) : archivedCountOf(session.id);
|
return instanceId(cfg.data_root) + ':' + (session.user || '-') + ':' + session.id +
|
||||||
return instanceId(cfg.data_root) + ':' + (session.user || '-') + ':' + session.id + ':' + n;
|
':' + archivedCount(session.history);
|
||||||
}
|
}
|
||||||
|
|
||||||
function saveMessage(sessionId, msg) {
|
function saveMessage(sessionId, msg) {
|
||||||
@@ -576,9 +569,8 @@ function killRunProcs(run) {
|
|||||||
for (const proc of run.procs) {
|
for (const proc of run.procs) {
|
||||||
// 远端 executor 任务句柄(remote-exec.js):发 DELETE 取消,不能本地 kill。
|
// 远端 executor 任务句柄(remote-exec.js):发 DELETE 取消,不能本地 kill。
|
||||||
if (typeof proc.remoteKill === 'function') { try { proc.remoteKill(); } catch (_) {} continue; }
|
if (typeof proc.remoteKill === 'function') { try { proc.remoteKill(); } catch (_) {} continue; }
|
||||||
try { process.kill(-proc.pid, 'SIGKILL'); } catch (_) {
|
// 平台差异交给执行后端:POSIX 杀进程组,Windows 走 taskkill /T。
|
||||||
try { proc.kill('SIGKILL'); } catch (__) {}
|
shell.killTree(proc);
|
||||||
}
|
|
||||||
}
|
}
|
||||||
run.procs.clear();
|
run.procs.clear();
|
||||||
}
|
}
|
||||||
@@ -881,11 +873,6 @@ async function runLoopInner(sessionId, run) {
|
|||||||
break;
|
break;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
lastErr = err;
|
lastErr = err;
|
||||||
// 无 upstream_status = 网络层失败或中断(含「停止」「立即发送」的 abort):relay 在收到
|
|
||||||
// 上游 200 头时就已 put,而这边没拿到响应头、指针还停在上一轮,不作废就会在下一轮把
|
|
||||||
// 重复的增量再拼一遍 → tool_call_mismatch。直接清指针,下一轮走全量 + Reset 覆盖。
|
|
||||||
// 有 upstream_status 的 429/5xx 则确定没写缓存,保留指针,重试发空增量最省。
|
|
||||||
if (!err.upstream_status) invalidateContext(contextIdOf(session));
|
|
||||||
const retriable = !err.upstream_status || err.upstream_status === 429 || err.upstream_status >= 500;
|
const retriable = !err.upstream_status || err.upstream_status === 429 || err.upstream_status >= 500;
|
||||||
if (!retriable || attempt === cfg.agent.max_retries) break;
|
if (!retriable || attempt === cfg.agent.max_retries) break;
|
||||||
// 重试用的是同一份 messages(数组一字未变),所以增量上下文会发空 body,
|
// 重试用的是同一份 messages(数组一字未变),所以增量上下文会发空 body,
|
||||||
@@ -898,9 +885,7 @@ async function runLoopInner(sessionId, run) {
|
|||||||
if (run.cancelled) break;
|
if (run.cancelled) break;
|
||||||
if (!result) {
|
if (!result) {
|
||||||
const text = '⚠️ 模型调用失败:' + (lastErr && lastErr.message || '未知错误');
|
const text = '⚠️ 模型调用失败:' + (lastErr && lastErr.message || '未知错误');
|
||||||
// type='error_note':留痕给 UI,但不进模型上下文(buildMessages 跳过),
|
const errId = saveMessage(sessionId, { role: 'assistant', content: text });
|
||||||
// 否则失败文案会当成模型的真实回复一直带下去。
|
|
||||||
const errId = saveMessage(sessionId, { role: 'assistant', content: text, type: 'error_note' });
|
|
||||||
bus.emit(sessionId, 'assistant_message', { id: errId, content: text, error: true, created_at: now() });
|
bus.emit(sessionId, 'assistant_message', { id: errId, content: text, error: true, created_at: now() });
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@@ -971,10 +956,10 @@ async function runLoopInner(sessionId, run) {
|
|||||||
recordModelUsage(sessionId, session.model_id, result.usage);
|
recordModelUsage(sessionId, session.model_id, result.usage);
|
||||||
// 回合级 In token 峰值:工具迭代只会越滚越大,取各轮 prompt_tokens 最大值作自动压缩判据
|
// 回合级 In token 峰值:工具迭代只会越滚越大,取各轮 prompt_tokens 最大值作自动压缩判据
|
||||||
if (msgRow.usage && msgRow.usage.pt > (run.turnMaxPt || 0)) run.turnMaxPt = msgRow.usage.pt;
|
if (msgRow.usage && msgRow.usage.pt > (run.turnMaxPt || 0)) run.turnMaxPt = msgRow.usage.pt;
|
||||||
// 「压缩」回合的总结判定:压缩指令发出去,模型回来的第一段非空文本就是摘要——带不带
|
// 「压缩」回合的总结判定:压缩时不传 tools,因此本回合第一条「无 tool_calls 的收尾回复」
|
||||||
// 工具都算(模型常为了把摘要写准先调一次工具查证,这一轮的文字同样是摘要,不能当普通
|
// 就是摘要(compressing 取自本回合的 run.summarizing 标记);回合中间若有异常产生的
|
||||||
// 回复落库)。空文本(纯工具调用、一个字没写)不算,run.summarizing 保持,下一轮继续压。
|
// 工具轮(理论上不会)都是普通消息,前端照常渲染。
|
||||||
const isSummary = compressing && !!String(msgRow.content || '').trim();
|
const isSummary = !hasTools && compressing;
|
||||||
bus.emit(sessionId, 'assistant_message', {
|
bus.emit(sessionId, 'assistant_message', {
|
||||||
id: assistantId, content: msgRow.content, reasoning: msgRow.reasoning,
|
id: assistantId, content: msgRow.content, reasoning: msgRow.reasoning,
|
||||||
tool_calls: msgRow.tool_calls, type: msgRow.type, created_at: msgRow.created_at,
|
tool_calls: msgRow.tool_calls, type: msgRow.type, created_at: msgRow.created_at,
|
||||||
@@ -999,19 +984,16 @@ async function runLoopInner(sessionId, run) {
|
|||||||
log.info('msg', sessionId + ' 压缩摘要 ' + assistantId + ' 落库,存档之前 ' + n + ' 条消息(不再发给模型)');
|
log.info('msg', sessionId + ' 压缩摘要 ' + assistantId + ' 落库,存档之前 ' + n + ' 条消息(不再发给模型)');
|
||||||
}
|
}
|
||||||
// 回合内自动压缩把正在跑的任务切成了摘要,摘要一落地就地续跑:
|
// 回合内自动压缩把正在跑的任务切成了摘要,摘要一落地就地续跑:
|
||||||
// 没有工具回执可用时补一条 user 指令接回原任务,否则会直接走到下面的 !hasTools 收尾,
|
// 补一条 user 指令接回原任务,否则会直接走到下面的 !hasTools 收尾,
|
||||||
// 任务停在半路,要用户再喊一声才动。有工具回执时不插消息也不 continue——落到下面
|
// 任务停在半路,要用户再喊一声才动。
|
||||||
// 执行工具,回执紧跟在摘要后面,本身就是续跑输入。
|
|
||||||
if (run.compactAuto) {
|
if (run.compactAuto) {
|
||||||
run.compactAuto = false;
|
run.compactAuto = false;
|
||||||
if (!hasTools) {
|
|
||||||
const resumeText = '上下文已压缩,请继续完成原任务。';
|
const resumeText = '上下文已压缩,请继续完成原任务。';
|
||||||
const resumeId = saveMessage(sessionId, { role: 'user', content: resumeText });
|
const resumeId = saveMessage(sessionId, { role: 'user', content: resumeText });
|
||||||
bus.emit(sessionId, 'user_message', { id: resumeId, content: resumeText, created_at: now() });
|
bus.emit(sessionId, 'user_message', { id: resumeId, content: resumeText, created_at: now() });
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
if (!hasTools) {
|
if (!hasTools) {
|
||||||
// 「干预」升级过的待投递消息:本条回复已落库,正是安全边界——直接插话并继续同一回合
|
// 「干预」升级过的待投递消息:本条回复已落库,正是安全边界——直接插话并继续同一回合
|
||||||
@@ -1056,20 +1038,9 @@ async function runLoopInner(sessionId, run) {
|
|||||||
output = chk.error;
|
output = chk.error;
|
||||||
isError = true;
|
isError = true;
|
||||||
} else {
|
} else {
|
||||||
// 工具执行中的增量输出(terminal 长命令):50ms 或 16KB 合并成一帧 SSE,避免逐行刷包
|
|
||||||
let liveBuf = '';
|
|
||||||
let liveTimer = null;
|
|
||||||
const flushLive = () => {
|
|
||||||
if (liveTimer) { clearTimeout(liveTimer); liveTimer = null; }
|
|
||||||
if (!liveBuf) return;
|
|
||||||
const chunk = liveBuf;
|
|
||||||
liveBuf = '';
|
|
||||||
bus.emit(sessionId, 'tool_output', { id, chunk });
|
|
||||||
};
|
|
||||||
try {
|
try {
|
||||||
output = await executeTool({ sessionId, taskDir: taskDirOf(sessionId), workDir: sessionWorkDir(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),
|
onTaskCreated: () => { run.taskWrap = true; }, onCard: (card) => bus.emit(sessionId, 'ui_card', card),
|
||||||
onOutput: (s) => { liveBuf += s; if (liveBuf.length >= 16384) flushLive(); else if (!liveTimer) liveTimer = setTimeout(flushLive, 50); },
|
|
||||||
onDeepThink: (info) => {
|
onDeepThink: (info) => {
|
||||||
const m = (cfg.models || []).find(x => x.id === session.model_id);
|
const m = (cfg.models || []).find(x => x.id === session.model_id);
|
||||||
const supported = !!(m && m.thinking_params && Object.keys(m.thinking_params).length);
|
const supported = !!(m && m.thinking_params && Object.keys(m.thinking_params).length);
|
||||||
@@ -1082,7 +1053,6 @@ async function runLoopInner(sessionId, run) {
|
|||||||
output = 'Error: ' + (err && err.message || String(err));
|
output = 'Error: ' + (err && err.message || String(err));
|
||||||
isError = true;
|
isError = true;
|
||||||
}
|
}
|
||||||
flushLive();
|
|
||||||
}
|
}
|
||||||
// 工具可返回 {text, image_rel}(read_file 读图且模型支持 vision,压缩产物在 .imgcache/,
|
// 工具可返回 {text, image_rel}(read_file 读图且模型支持 vision,压缩产物在 .imgcache/,
|
||||||
// text 是 imageReceipt 生成的结构化 JSON 回执):落库时以 image_ref 内容块拼进 tool 消息
|
// text 是 imageReceipt 生成的结构化 JSON 回执):落库时以 image_ref 内容块拼进 tool 消息
|
||||||
|
|||||||
+1
-4
@@ -310,8 +310,6 @@ function buildMessages(session, language, mintUrl, profile, withProfile, trimOn)
|
|||||||
history.forEach((row, i) => {
|
history.forEach((row, i) => {
|
||||||
// archived:UI 可见,但不进入模型上下文(节省 token)
|
// archived:UI 可见,但不进入模型上下文(节省 token)
|
||||||
if (row.type === 'archived') return;
|
if (row.type === 'archived') return;
|
||||||
// error_note:失败文案,只给 UI 留痕,不进模型(否则被当成模型的真实回复带下去)
|
|
||||||
if (row.type === 'error_note') return;
|
|
||||||
// summarize_request(旧版遗留行):仅在未收尾的旧压缩回合内发给模型,其余一律跳过
|
// summarize_request(旧版遗留行):仅在未收尾的旧压缩回合内发给模型,其余一律跳过
|
||||||
if (row.type === 'summarize_request') {
|
if (row.type === 'summarize_request') {
|
||||||
if (i > lastClosingAssistant && (row.content || '').trim()) {
|
if (i > lastClosingAssistant && (row.content || '').trim()) {
|
||||||
@@ -538,8 +536,7 @@ function trimToolContent(content, row, callById, roundsAfter, turnsAfter) {
|
|||||||
// 拼压缩回合的 messages(参考 titleMessages 的拼法):默认 system prompt + 正常历史
|
// 拼压缩回合的 messages(参考 titleMessages 的拼法):默认 system prompt + 正常历史
|
||||||
//(与 buildMessages 同取舍:archived 不发、旧摘要/工具轮照常),末尾追加一条 user
|
//(与 buildMessages 同取舍:archived 不发、旧摘要/工具轮照常),末尾追加一条 user
|
||||||
//(prompt-compress.txt 原文,历史就在它前面的 messages 里,不再填占位符)。
|
//(prompt-compress.txt 原文,历史就在它前面的 messages 里,不再填占位符)。
|
||||||
// 调用方(engine.runLoopInner 的 compressing 分支)照常带 tools:工具段在最前,删掉等于断整段
|
// 调用方(engine.runLoopInner 的 compressing 分支)需同时不传 tools。
|
||||||
// 前缀缓存;模型偶尔会为核对事实调一次,那一轮的文字仍按摘要处理(见 isSummary 判定)。
|
|
||||||
// 【缓存铁律】压缩请求必须与上一次常规请求字节同构、只在尾部追加指令:画像快照与
|
// 【缓存铁律】压缩请求必须与上一次常规请求字节同构、只在尾部追加指令:画像快照与
|
||||||
// 占位裁剪一律照常(不传 withProfile/trim = 同一拼法),也不裁历史中间任何注入行——
|
// 占位裁剪一律照常(不传 withProfile/trim = 同一拼法),也不裁历史中间任何注入行——
|
||||||
// 从首个被删/被改动行起前缀缓存全断,等于全价重读(旧代码 withProfile=false 把坐在
|
// 从首个被删/被改动行起前缀缓存全断,等于全价重读(旧代码 withProfile=false 把坐在
|
||||||
|
|||||||
@@ -432,14 +432,6 @@ main { flex: 1; min-height: 0; display: flex; flex-direction: column; }
|
|||||||
border-top: 1px solid var(--border);
|
border-top: 1px solid var(--border);
|
||||||
background: var(--bg-fafbfd);
|
background: var(--bg-fafbfd);
|
||||||
}
|
}
|
||||||
/* 流式思考:面板保持折叠,只在标题行挂一段动态文字(.msg-think-live),
|
|
||||||
正文开始后清空。不占额外高度,也不会大段刷屏;要看全文点开就是落库的那份。 */
|
|
||||||
.msg-think.streaming { pointer-events: none; }
|
|
||||||
.msg-think-live {
|
|
||||||
flex: 1; min-width: 0; margin-left: 8px;
|
|
||||||
overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
|
|
||||||
font-size: 12px; font-weight: 400; color: var(--gray-light);
|
|
||||||
}
|
|
||||||
/* 流式阶段给一点视觉提示:边色稍亮,收尾(assistant_message)后去除 */
|
/* 流式阶段给一点视觉提示:边色稍亮,收尾(assistant_message)后去除 */
|
||||||
.msg-think.streaming { border-color: var(--bd-d8e0f5); }
|
.msg-think.streaming { border-color: var(--bd-d8e0f5); }
|
||||||
|
|
||||||
@@ -614,7 +606,8 @@ footer { position: relative; flex: none; padding: 8px 12px calc(10px + var(--sab
|
|||||||
.attach-chip .name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 140px; }
|
.attach-chip .name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 140px; }
|
||||||
.attach-chip .rm { color: var(--gray); display: flex; }
|
.attach-chip .rm { color: var(--gray); display: flex; }
|
||||||
/* 工具卡参数流式生成中:◌ 呼吸提示(收尾后随 .tool-generating 移除) */
|
/* 工具卡参数流式生成中:◌ 呼吸提示(收尾后随 .tool-generating 移除) */
|
||||||
.tool-card.tool-generating .spin { animation: tool-spin 0.9s linear infinite; }
|
.tool-card.tool-generating .spin { display: inline-block; color: var(--active); animation: tool-gen-pulse 1s ease-in-out infinite; }
|
||||||
|
@keyframes tool-gen-pulse { 0%, 100% { opacity: 1 } 50% { opacity: .2 } }
|
||||||
|
|
||||||
/* 上传文件卡片行(嵌在输入框内部顶端,由 .input-shell 的 gap 提供间距;逐卡进度遮罩;卡多时横向滚动) */
|
/* 上传文件卡片行(嵌在输入框内部顶端,由 .input-shell 的 gap 提供间距;逐卡进度遮罩;卡多时横向滚动) */
|
||||||
.up-cards {
|
.up-cards {
|
||||||
@@ -1389,12 +1382,7 @@ body.voice-active .scroll-bottom-btn { display: none; }
|
|||||||
.tool-card .tool-time .act svg { width: 12px; height: 12px; }
|
.tool-card .tool-time .act svg { width: 12px; height: 12px; }
|
||||||
.tool-card .tool-time .act.copied { color: var(--fg-2e7d32); }
|
.tool-card .tool-time .act.copied { color: var(--fg-2e7d32); }
|
||||||
.tool-card.error { background: var(--bg-fdecea); border-color: var(--bd-f2c4bd); color: var(--fg-a3352a); }
|
.tool-card.error { background: var(--bg-fdecea); border-color: var(--bd-f2c4bd); color: var(--fg-a3352a); }
|
||||||
.tool-card .spin { display: inline-flex; align-items: center; justify-content: center; width: 1em; height: 1em; }
|
.tool-card .spin { display: inline-block; width: 1em; text-align: center; }
|
||||||
.tool-card .spin svg { width: 100%; height: 100%; }
|
|
||||||
/* 执行中:摘要行左侧那段弧转起来。动画挂在 .spin 容器上——直接转 SVG 元素时
|
|
||||||
CSS transform 的默认原点在左上角(0 0),会绕着角转,看着像没动 */
|
|
||||||
.tool-card.running .spin { animation: tool-spin 0.9s linear infinite; }
|
|
||||||
@keyframes tool-spin { to { transform: rotate(360deg); } }
|
|
||||||
.tool-card .tool-args-full { color: var(--fg-6b5b2a); }
|
.tool-card .tool-args-full { color: var(--fg-6b5b2a); }
|
||||||
/* 工具结果里的图片(read_file 读图回传;点击放大查看) */
|
/* 工具结果里的图片(read_file 读图回传;点击放大查看) */
|
||||||
.tool-img {
|
.tool-img {
|
||||||
@@ -1551,16 +1539,6 @@ label.icon-btn { cursor: pointer; }
|
|||||||
.cfg-input:focus { border-color: var(--active); background: var(--bg-fff); }
|
.cfg-input:focus { border-color: var(--active); background: var(--bg-fff); }
|
||||||
.cfg-input::-webkit-outer-spin-button, .cfg-input::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; }
|
.cfg-input::-webkit-outer-spin-button, .cfg-input::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; }
|
||||||
.cfg-input.cfg-dirty { color: var(--fg-c0392b); border-color: var(--bd-e8b4b0); background: var(--bg-fdf3f2); }
|
.cfg-input.cfg-dirty { color: var(--fg-c0392b); border-color: var(--bd-e8b4b0); background: var(--bg-fdf3f2); }
|
||||||
/* 多行条目输入(如画像偏好):标签在上、输入框占整行,便于一行一条 */
|
|
||||||
.cfg-kv.stack { flex-direction: column; align-items: stretch; gap: 6px; }
|
|
||||||
.cfg-kv.stack label { max-width: none; }
|
|
||||||
.cfg-textarea {
|
|
||||||
width: 100%; min-height: 96px; box-sizing: border-box; resize: vertical;
|
|
||||||
font-size: 13px; line-height: 1.7; color: var(--ink); font-family: inherit;
|
|
||||||
text-align: left; background: var(--surface); border: 1px solid transparent;
|
|
||||||
border-radius: 8px; padding: 8px 10px; -webkit-appearance: none; appearance: none;
|
|
||||||
}
|
|
||||||
.cfg-textarea:focus { border-color: var(--active); background: var(--bg-fff); outline: none; }
|
|
||||||
.cfg-err {
|
.cfg-err {
|
||||||
margin: 0 0 8px; padding: 8px 12px; border-radius: 8px;
|
margin: 0 0 8px; padding: 8px 12px; border-radius: 8px;
|
||||||
background: var(--bg-fdecea); color: var(--fg-a3352a); font-size: 12.5px;
|
background: var(--bg-fdecea); color: var(--fg-a3352a); font-size: 12.5px;
|
||||||
|
|||||||
@@ -192,7 +192,7 @@
|
|||||||
const gen = !!(opts && opts.generating);
|
const gen = !!(opts && opts.generating);
|
||||||
if (gen) div.classList.add('tool-generating');
|
if (gen) div.classList.add('tool-generating');
|
||||||
div.innerHTML =
|
div.innerHTML =
|
||||||
'<details' + (open ? ' open' : '') + '><summary><span class="spin"><svg class="ic sm" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><path d="M21 12a9 9 0 1 1-6.2-8.6"/></svg></span>' +
|
'<details' + (open ? ' open' : '') + '><summary><span class="spin">◌</span>' +
|
||||||
'<span class="tool-name">' + esc(name) + '</span>' +
|
'<span class="tool-name">' + esc(name) + '</span>' +
|
||||||
'<span class="tool-args">' + (gen ? '生成参数中…' : esc(toolArgsSummary(name, argsStr))) + '</span></summary>' +
|
'<span class="tool-args">' + (gen ? '生成参数中…' : esc(toolArgsSummary(name, argsStr))) + '</span></summary>' +
|
||||||
'<pre class="tool-args-full">' + (gen ? '' : esc(toolArgsFull(argsStr))) + '</pre>' +
|
'<pre class="tool-args-full">' + (gen ? '' : esc(toolArgsFull(argsStr))) + '</pre>' +
|
||||||
@@ -249,10 +249,7 @@
|
|||||||
const card = document.getElementById('tool-' + id);
|
const card = document.getElementById('tool-' + id);
|
||||||
if (!card) return;
|
if (!card) return;
|
||||||
if (isError) card.classList.add('error');
|
if (isError) card.classList.add('error');
|
||||||
card.classList.remove('running'); // 停止转圈,换成结果标记
|
card.querySelector('.spin').textContent = isError ? '✕' : '✓';
|
||||||
card.querySelector('.spin').innerHTML = isError
|
|
||||||
? '<svg class="ic sm" viewBox="0 0 24 24"><use href="#i-x-line"/></svg>'
|
|
||||||
: '<svg class="ic sm" viewBox="0 0 24 24"><use href="#i-check"/></svg>';
|
|
||||||
const parsed = parseToolContent(content);
|
const parsed = parseToolContent(content);
|
||||||
const pre = card.querySelector('.tool-result');
|
const pre = card.querySelector('.tool-result');
|
||||||
if (!pre) return;
|
if (!pre) return;
|
||||||
@@ -277,20 +274,6 @@
|
|||||||
pre.insertAdjacentElement('afterend', el);
|
pre.insertAdjacentElement('afterend', el);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// 工具执行中的增量输出(terminal 长命令):边跑边填;只留尾部 2000 行,避免长跑命令撑爆 DOM
|
|
||||||
function appendToolOutput(id, chunk) {
|
|
||||||
const card = document.getElementById('tool-' + id);
|
|
||||||
if (!card) return;
|
|
||||||
const pre = card.querySelector('.tool-result');
|
|
||||||
if (!pre) return;
|
|
||||||
if (!pre.dataset.streaming) { pre.textContent = ''; pre.dataset.streaming = '1'; } // 首块到达:清掉“执行中…”占位
|
|
||||||
const follow = pre.scrollHeight - pre.scrollTop - pre.clientHeight < 8; // 用户往上翻时不抢滚动
|
|
||||||
pre.appendChild(document.createTextNode(chunk));
|
|
||||||
const lines = pre.textContent.split('\n');
|
|
||||||
if (lines.length > 2000) pre.textContent = '…(更早输出已折叠)\n' + lines.slice(-2000).join('\n');
|
|
||||||
// 追加后滚到底:读 scrollHeight 会强制布局拿到新高度;再补一帧,避免大 chunk 一次没贴到底
|
|
||||||
if (follow) { pre.scrollTop = pre.scrollHeight; requestAnimationFrame(() => { pre.scrollTop = pre.scrollHeight; }); }
|
|
||||||
}
|
|
||||||
// 把 assistant 消息里的 tool_calls 建成工具卡片(历史渲染与 assistant_message 事件共用)
|
// 把 assistant 消息里的 tool_calls 建成工具卡片(历史渲染与 assistant_message 事件共用)
|
||||||
function appendToolCardsFromAssistant(m, container) {
|
function appendToolCardsFromAssistant(m, container) {
|
||||||
if (!m.tool_calls) return;
|
if (!m.tool_calls) return;
|
||||||
|
|||||||
@@ -362,55 +362,29 @@
|
|||||||
} catch (e) { toast('修改失败:' + e.message); }
|
} catch (e) { toast('修改失败:' + e.message); }
|
||||||
}
|
}
|
||||||
// ---------- 页:账户——用户画像编辑卡直接渲染在账户页(无二级页;保存后 renderSetPage 重拉刷新停用徽标) ----------
|
// ---------- 页:账户——用户画像编辑卡直接渲染在账户页(无二级页;保存后 renderSetPage 重拉刷新停用徽标) ----------
|
||||||
const PREF_MAX = 1000; // 与后端 user-profile.js 的 PREF_MAX 对齐
|
|
||||||
const PROFILE_FIELDS = [
|
const PROFILE_FIELDS = [
|
||||||
['honorific', '称谓', '希望被怎么称呼', 80],
|
['honorific', '称谓', '希望被怎么称呼', 80],
|
||||||
['industry', '行业', '影响术语与默认假设', 80],
|
['industry', '行业', '影响术语与默认假设', 80],
|
||||||
['preference', '偏好', '一行一条', 0, 'textarea'],
|
['preference', '偏好', '顿号分隔标签(AI 会在沟通中自动补充,可手动增删)', 300],
|
||||||
];
|
];
|
||||||
function prefCountText(n) {
|
|
||||||
return '已用 ' + n + ' / ' + PREF_MAX + ' 字' + (n > PREF_MAX ? ',超出部分保存时截断' : '');
|
|
||||||
}
|
|
||||||
function prefCount() {
|
|
||||||
const el = $('prof-preference'), out = $('prof-count-preference');
|
|
||||||
if (!el || !out) return;
|
|
||||||
const n = el.value.trim().length;
|
|
||||||
out.textContent = prefCountText(n);
|
|
||||||
out.style.color = n > PREF_MAX ? 'var(--fg-c0392b)' : '';
|
|
||||||
}
|
|
||||||
function profileCardHtml(p) {
|
function profileCardHtml(p) {
|
||||||
let html = '<div class="settings-card"><h4>用户画像' +
|
let html = '<div class="settings-card"><h4>用户画像' +
|
||||||
(p.enabled === false ? ' <span class="badge held">已停用</span>' : '') + '</h4>' +
|
(p.enabled === false ? ' <span class="badge held">已停用</span>' : '') + '</h4>' +
|
||||||
'<div class="cfg-kv"><label>启用</label><input type="checkbox" id="prof-enabled"' + (p.enabled === false ? '' : ' checked') + '></div>';
|
'<div class="cfg-kv"><label>启用</label><input type="checkbox" id="prof-enabled"' + (p.enabled === false ? '' : ' checked') + '></div>';
|
||||||
for (const [k, name, ph, maxLen, kind] of PROFILE_FIELDS) {
|
for (const [k, name, ph, maxLen] of PROFILE_FIELDS) {
|
||||||
const v = String(p[k] || '');
|
const v = String(p[k] || '');
|
||||||
if (kind === 'textarea') {
|
|
||||||
// 用户输入什么就存什么、注入什么:不拆不拼、不规范化分隔符,换行原样保留
|
|
||||||
html += '<div class="cfg-kv stack"><label>' + esc(name) + '</label>' +
|
|
||||||
'<textarea class="cfg-textarea" id="prof-' + k + '" rows="8" placeholder="' + esc(ph) + '" oninput="sUI.prefCount()">' + esc(v) + '</textarea>' +
|
|
||||||
'<div class="cfg-note" id="prof-count-' + k + '">' + prefCountText(v.length) + '</div></div>';
|
|
||||||
} else {
|
|
||||||
html += '<div class="cfg-kv"><label>' + esc(name) + '</label>' +
|
html += '<div class="cfg-kv"><label>' + esc(name) + '</label>' +
|
||||||
'<input class="cfg-input" id="prof-' + k + '" type="text" maxlength="' + (maxLen || 80) + '" data-orig="' + att(v) + '" value="' + att(v) + '" placeholder="' + esc(ph) + '"></div>';
|
'<input class="cfg-input" id="prof-' + k + '" type="text" maxlength="' + (maxLen || 80) + '" data-orig="' + att(v) + '" value="' + att(v) + '" placeholder="' + esc(ph) + '"></div>';
|
||||||
}
|
}
|
||||||
}
|
|
||||||
html += '<button class="primary-btn" style="margin-top:8px" onclick="sUI.saveProfile()">保存</button>' +
|
html += '<button class="primary-btn" style="margin-top:8px" onclick="sUI.saveProfile()">保存</button>' +
|
||||||
'<div class="cfg-note">新会话生效</div></div>';
|
'<div class="cfg-note">画像只记「不知道就会做错」的信息,新会话开始时作为背景注入(会话内不更新;清空字段保存即抹除)。' +
|
||||||
|
'AI 会在沟通中持续维护(尤其偏好标签,只记明确表达过的,写入自下个会话生效),这里手动改随时可覆盖。' +
|
||||||
|
'停用后不再注入,AI 的记录请求也会被拒。近期关注(最近会话标题)自动带入背景,无需维护。</div></div>';
|
||||||
return html;
|
return html;
|
||||||
}
|
}
|
||||||
async function saveProfile() {
|
async function saveProfile() {
|
||||||
const body = { enabled: $('prof-enabled').checked };
|
const body = { enabled: $('prof-enabled').checked };
|
||||||
for (const [k, , , , kind] of PROFILE_FIELDS) {
|
for (const [k] of PROFILE_FIELDS) { const el = $('prof-' + k); if (el) body[k] = el.value.trim(); }
|
||||||
const el = $('prof-' + k);
|
|
||||||
if (!el) continue;
|
|
||||||
const v = el.value.trim();
|
|
||||||
if (kind === 'textarea' && v.length > PREF_MAX) {
|
|
||||||
body[k] = v.slice(0, PREF_MAX);
|
|
||||||
toast('偏好超过 ' + PREF_MAX + ' 字,已截断保存');
|
|
||||||
} else {
|
|
||||||
body[k] = v;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
try { await req('PUT', '/api/profile', body); toast('已保存,新会话生效'); renderSetPage(); }
|
try { await req('PUT', '/api/profile', body); toast('已保存,新会话生效'); renderSetPage(); }
|
||||||
catch (e) { toast('保存失败:' + e.message); }
|
catch (e) { toast('保存失败:' + e.message); }
|
||||||
}
|
}
|
||||||
@@ -2024,7 +1998,6 @@
|
|||||||
// 账户
|
// 账户
|
||||||
changePassword: changePassword,
|
changePassword: changePassword,
|
||||||
saveProfile: saveProfile,
|
saveProfile: saveProfile,
|
||||||
prefCount: prefCount,
|
|
||||||
// 用户管理(仅管理员)
|
// 用户管理(仅管理员)
|
||||||
openUserAdd: openUserAdd,
|
openUserAdd: openUserAdd,
|
||||||
openUserEdit: openUserEditor,
|
openUserEdit: openUserEditor,
|
||||||
|
|||||||
@@ -182,16 +182,15 @@
|
|||||||
state.streamEl = bubble;
|
state.streamEl = bubble;
|
||||||
return wrap;
|
return wrap;
|
||||||
}
|
}
|
||||||
// 思考面板:首次思考 delta 到达时创建。**不展开**,只在 summary 里挂一段动态文字,
|
// 思考面板:首次思考 delta 到达时创建,带 open 状态(流式中默认展开)
|
||||||
// 让人感觉到在干活;正文开始后清空那段文字,需要看全文再点开。
|
|
||||||
function ensureStreamThinkPanel() {
|
function ensureStreamThinkPanel() {
|
||||||
if (state.streamThinkEl) return state.streamThinkEl;
|
if (state.streamThinkEl) return state.streamThinkEl;
|
||||||
if (!state.streamWrap) ensureStreamWrap();
|
if (!state.streamWrap) ensureStreamWrap();
|
||||||
const det = document.createElement('details');
|
const det = document.createElement('details');
|
||||||
det.className = 'msg-think streaming';
|
det.className = 'msg-think streaming';
|
||||||
det.open = false; // 流式阶段也不展开:展开的大段思考会把下面的内容一路顶下去
|
det.open = true; // 流式阶段默认展开,看思考增量
|
||||||
const sum = document.createElement('summary');
|
const sum = document.createElement('summary');
|
||||||
sum.innerHTML = '思考过程<span class="msg-think-live"></span>' + THINK_COPY_BTN;
|
sum.innerHTML = '思考过程' + THINK_COPY_BTN;
|
||||||
const body = document.createElement('div');
|
const body = document.createElement('div');
|
||||||
body.className = 'msg-think-body';
|
body.className = 'msg-think-body';
|
||||||
det.appendChild(sum);
|
det.appendChild(sum);
|
||||||
@@ -199,12 +198,10 @@
|
|||||||
// 插在气泡之前(思考 → 结论 的顺序)
|
// 插在气泡之前(思考 → 结论 的顺序)
|
||||||
state.streamWrap.insertBefore(det, state.streamEl);
|
state.streamWrap.insertBefore(det, state.streamEl);
|
||||||
state.streamThinkEl = body;
|
state.streamThinkEl = body;
|
||||||
state.streamThinkLive = sum.querySelector('.msg-think-live');
|
|
||||||
return body;
|
return body;
|
||||||
}
|
}
|
||||||
// 思考结束(正文开始流式或本轮收尾):清空标题行那段动态文字、折叠面板、去掉流式标记
|
// 思考结束(正文开始流式或本轮收尾):自动折叠思考面板并去掉流式高亮边框;用户仍可手动点开回看
|
||||||
function collapseStreamThink() {
|
function collapseStreamThink() {
|
||||||
if (state.streamThinkLive) state.streamThinkLive.textContent = '';
|
|
||||||
if (!state.streamThinkEl) return;
|
if (!state.streamThinkEl) return;
|
||||||
const det = state.streamThinkEl.closest('details');
|
const det = state.streamThinkEl.closest('details');
|
||||||
if (det) { det.open = false; det.classList.remove('streaming'); }
|
if (det) { det.open = false; det.classList.remove('streaming'); }
|
||||||
@@ -226,22 +223,13 @@
|
|||||||
el.textContent = full; // 结构不符(收尾后重建/罕见回退)才整段重写
|
el.textContent = full; // 结构不符(收尾后重建/罕见回退)才整段重写
|
||||||
}
|
}
|
||||||
|
|
||||||
// 标题行里的动态文字:只取最后一行(单行截断),持续换内容形成“在动”的感觉。
|
|
||||||
// 不能像正文那样 appendData:这里是一行标题,追加只会无限变长。
|
|
||||||
function paintThinkLive(el, full) {
|
|
||||||
if (!el) return;
|
|
||||||
const lines = String(full || '').split('\n').filter(Boolean);
|
|
||||||
const tail = lines.length ? lines[lines.length - 1] : '';
|
|
||||||
if (el.textContent !== tail) el.textContent = tail;
|
|
||||||
}
|
|
||||||
|
|
||||||
function scheduleStreamPaint() {
|
function scheduleStreamPaint() {
|
||||||
if (streamPaintQueued) return;
|
if (streamPaintQueued) return;
|
||||||
streamPaintQueued = true;
|
streamPaintQueued = true;
|
||||||
requestAnimationFrame(() => {
|
requestAnimationFrame(() => {
|
||||||
streamPaintQueued = false;
|
streamPaintQueued = false;
|
||||||
paintStreamingText(state.streamEl, state.streamText);
|
paintStreamingText(state.streamEl, state.streamText);
|
||||||
paintThinkLive(state.streamThinkLive, state.streamReasoning);
|
paintStreamingText(state.streamThinkEl, state.streamReasoning);
|
||||||
maybeAutoScroll();
|
maybeAutoScroll();
|
||||||
updateScrollBottomBtn();
|
updateScrollBottomBtn();
|
||||||
});
|
});
|
||||||
@@ -255,7 +243,7 @@
|
|||||||
state.lastSseAt = Date.now(); // 建连即重置静默计时
|
state.lastSseAt = Date.now(); // 建连即重置静默计时
|
||||||
// 任何具名事件都算连接存活:静默看门狗与回前台宽限共用(error 不列,原生连接错误也走 error)
|
// 任何具名事件都算连接存活:静默看门狗与回前台宽限共用(error 不列,原生连接错误也走 error)
|
||||||
['ping', 'status', 'assistant_delta', 'reasoning_delta', 'assistant_message', 'tool_call_start',
|
['ping', 'status', 'assistant_delta', 'reasoning_delta', 'assistant_message', 'tool_call_start',
|
||||||
'tool_call_args', 'tool_call', 'tool_output', 'tool_result', 'ui_card', 'auto_compress', 'done', 'title', 'think_auto',
|
'tool_call_args', 'tool_call', 'tool_result', 'ui_card', 'auto_compress', 'done', 'title', 'think_auto',
|
||||||
'pending_added', 'pending_removed', 'user_message']
|
'pending_added', 'pending_removed', 'user_message']
|
||||||
.forEach(function (n) { es.addEventListener(n, function () { markSseAlive(n); }); });
|
.forEach(function (n) { es.addEventListener(n, function () { markSseAlive(n); }); });
|
||||||
es.addEventListener('status', ev => {
|
es.addEventListener('status', ev => {
|
||||||
@@ -428,20 +416,14 @@
|
|||||||
if (state.toolCards[d.id]) {
|
if (state.toolCards[d.id]) {
|
||||||
// 执行时的完整参数事件:若为流式早卡则回填收尾(unwrap 后的干净参数),普通卡不动
|
// 执行时的完整参数事件:若为流式早卡则回填收尾(unwrap 后的干净参数),普通卡不动
|
||||||
finalizeToolCardArgs(d.id, d.name, d.arguments);
|
finalizeToolCardArgs(d.id, d.name, d.arguments);
|
||||||
state.toolCards[d.id].classList.add('running'); // 执行中:摘要行圆点转起来
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// 无早卡(旧行为/刷新后重连):直接建展开卡
|
// 无早卡(旧行为/刷新后重连):直接建展开卡
|
||||||
const card = renderToolCard(d.id, d.name, d.arguments, Date.now(), { open: true });
|
const card = renderToolCard(d.id, d.name, d.arguments, Date.now(), { open: true });
|
||||||
card.classList.add('running');
|
|
||||||
$('chat-view').appendChild(card);
|
$('chat-view').appendChild(card);
|
||||||
state.toolCards[d.id] = card;
|
state.toolCards[d.id] = card;
|
||||||
maybeAutoScroll();
|
maybeAutoScroll();
|
||||||
});
|
});
|
||||||
es.addEventListener('tool_output', ev => {
|
|
||||||
const d = JSON.parse(ev.data);
|
|
||||||
appendToolOutput(d.id, d.chunk);
|
|
||||||
});
|
|
||||||
es.addEventListener('tool_result', ev => {
|
es.addEventListener('tool_result', ev => {
|
||||||
const d = JSON.parse(ev.data);
|
const d = JSON.parse(ev.data);
|
||||||
fillToolResult(d.tool_call_id, d.content, d.is_error, d.image_url, d.msg_id);
|
fillToolResult(d.tool_call_id, d.content, d.is_error, d.image_url, d.msg_id);
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ function reqHeaders(cfg) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 执行一条命令。返回 { code, killed_by, out };传输层失败抛 Error(由调用方决定如何呈现)。
|
// 执行一条命令。返回 { code, killed_by, out };传输层失败抛 Error(由调用方决定如何呈现)。
|
||||||
// opts: { command, cwd?, timeout_ms?, env?, run?, onChunk? }(run = engine 的 {cancelled, procs},可省略)
|
// opts: { command, cwd?, timeout_ms?, env?, run? }(run = engine 的 {cancelled, procs},可省略)
|
||||||
async function run(cfg, opts) {
|
async function run(cfg, opts) {
|
||||||
const base = cfg.executor.url;
|
const base = cfg.executor.url;
|
||||||
const timeoutMs = opts.timeout_ms && opts.timeout_ms > 0 ? opts.timeout_ms : 300000;
|
const timeoutMs = opts.timeout_ms && opts.timeout_ms > 0 ? opts.timeout_ms : 300000;
|
||||||
@@ -73,11 +73,7 @@ async function run(cfg, opts) {
|
|||||||
let ev;
|
let ev;
|
||||||
try { ev = JSON.parse(line.slice(6)); } catch (_) { continue; }
|
try { ev = JSON.parse(line.slice(6)); } catch (_) { continue; }
|
||||||
if (ev.type === 'start') id = ev.id;
|
if (ev.type === 'start') id = ev.id;
|
||||||
else if (ev.type === 'out' || ev.type === 'err') {
|
else if (ev.type === 'out' || ev.type === 'err') out += ev.chunk;
|
||||||
out += ev.chunk;
|
|
||||||
// 增量回调(UI 实时显示用):失败不影响主流程
|
|
||||||
if (opts.onChunk) { try { opts.onChunk(ev.chunk); } catch (_) {} }
|
|
||||||
}
|
|
||||||
else if (ev.type === 'exit') { exit = ev; break outer; }
|
else if (ev.type === 'exit') { exit = ev; break outer; }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,8 +13,8 @@ const scheduler = require('./scheduler');
|
|||||||
const wechat = require('./wechat');
|
const wechat = require('./wechat');
|
||||||
const llm = require('./llm');
|
const llm = require('./llm');
|
||||||
const mcp = require('./mcp');
|
const mcp = require('./mcp');
|
||||||
const devices = require('./devices');
|
|
||||||
const skills = require('./tools/skills');
|
const skills = require('./tools/skills');
|
||||||
|
const shellBackend = require('./shell');
|
||||||
const log = require('./log');
|
const log = require('./log');
|
||||||
|
|
||||||
const cfg = loadConfig(process.env.AGENT_CONFIG);
|
const cfg = loadConfig(process.env.AGENT_CONFIG);
|
||||||
@@ -49,11 +49,6 @@ wechat.init(cfg, db, bus);
|
|||||||
const app = express();
|
const app = express();
|
||||||
const server = http.createServer(app);
|
const server = http.createServer(app);
|
||||||
|
|
||||||
// 设备接入(devices.js):设备主动出站连 wss://<公网前缀>/dev/ws。
|
|
||||||
// 只在「有公网前缀 + 配了 DEVICE_TOKEN」时真正挂升级处理器,本地部署静默跳过。
|
|
||||||
devices.init(cfg);
|
|
||||||
devices.attach(server);
|
|
||||||
|
|
||||||
// wxbot 内网回调(/wxhook/inbox|hook):凭共享服务 token(Bearer)把门,微信用户永远不该直接碰
|
// wxbot 内网回调(/wxhook/inbox|hook):凭共享服务 token(Bearer)把门,微信用户永远不该直接碰
|
||||||
// 这两个端点(wxbot 只挂内网)。必须挂在全局 express.json(2mb) 之前:媒体 base64 转发体远超 2mb,
|
// 这两个端点(wxbot 只挂内网)。必须挂在全局 express.json(2mb) 之前:媒体 base64 转发体远超 2mb,
|
||||||
// 由 hookRouter 自带的 32mb 解析器先读掉并置 req._body,下游全局 json 解析器自动跳过(同 executor 不冲突)。
|
// 由 hookRouter 自带的 32mb 解析器先读掉并置 req._body,下游全局 json 解析器自动跳过(同 executor 不冲突)。
|
||||||
@@ -249,6 +244,10 @@ mcp.init(cfg).then(async () => {
|
|||||||
log.info('startup', ' auth=' + (auth.enabled ? 'login: ' + cfg.auth.users.map(u => u.user).join(', ') : '(disabled)'));
|
log.info('startup', ' auth=' + (auth.enabled ? 'login: ' + cfg.auth.users.map(u => u.user).join(', ') : '(disabled)'));
|
||||||
log.info('startup', ' wxbot=' + (cfg.wxbot.url && cfg.wxbot.token ? cfg.wxbot.url : '(未启用)'));
|
log.info('startup', ' wxbot=' + (cfg.wxbot.url && cfg.wxbot.token ? cfg.wxbot.url : '(未启用)'));
|
||||||
log.info('startup', ' log_level=' + cfg.log_level);
|
log.info('startup', ' log_level=' + cfg.log_level);
|
||||||
|
// 模型命令到底交给谁跑。硬定 shell 时这里是唯一的凭据(Windows 上尤其要看到);
|
||||||
|
// 探测不到就降成 warn——服务能起,但 terminal 工具会一片红。
|
||||||
|
if (shellBackend.resolve(cfg)) log.info('startup', ' terminal=' + shellBackend.describe(cfg));
|
||||||
|
else log.warn('startup', ' terminal=' + shellBackend.describe(cfg));
|
||||||
// 微信实例恢复 fire-and-forget:wxbot 没起只留日志,绝不阻塞/抛错影响启动。
|
// 微信实例恢复 fire-and-forget:wxbot 没起只留日志,绝不阻塞/抛错影响启动。
|
||||||
wechat.restore().catch(e => log.warn('wechat', '启动恢复异常:' + (e && e.message || e)));
|
wechat.restore().catch(e => log.warn('wechat', '启动恢复异常:' + (e && e.message || e)));
|
||||||
// prompt dump 失败不影响服务:只是核对用产物。
|
// prompt dump 失败不影响服务:只是核对用产物。
|
||||||
|
|||||||
@@ -0,0 +1,226 @@
|
|||||||
|
// 执行后端:全仓唯一处理「用哪个 shell 跑命令」「怎么杀整棵进程树」的地方。
|
||||||
|
//
|
||||||
|
// 为什么单开一层:POSIX 上 spawn('/bin/sh') + kill(-pid) 是刻意选的最强约束——
|
||||||
|
// /bin/sh 固定(不读 $SHELL,否则用户把 shell 设成 fish 后模型写的 POSIX 语法全废),
|
||||||
|
// 进程组让「停止」能一次带走模型起的孙进程(npm / python / ffmpeg 留下的才是麻烦)。
|
||||||
|
// Windows 没有 /bin/sh、没有进程组、也没有可发送的信号:同一个写法在那边从「有效」
|
||||||
|
// 变成「静默失效」,detached 还会多弹一个控制台。三种能力收敛成
|
||||||
|
// resolve / spawnShell / killTree,上层(terminal、skill、engine 取消)就不必出现平台分支。
|
||||||
|
//
|
||||||
|
// 默认行为与拆分前逐字节一致:不配任何 env 时仍是 /bin/sh -c + 进程组 +
|
||||||
|
// process.kill(-pid)。Windows 才走探测分支,探测不到就明确报错,绝不静默退回
|
||||||
|
// cmd.exe——cmd 的语法与模型写的 POSIX 差太远,静默降级只会让模型在报错里反复试错。
|
||||||
|
//
|
||||||
|
// 解析顺序(前面的赢,结果进程内缓存一次,与 config.js 的冷加载约定一致):
|
||||||
|
// 1. env AGENT_SHELL 显式指定可执行文件(绝对路径或 PATH 里的名字)
|
||||||
|
// 2. config.terminal.shell 同上,给不想碰 env 的部署方式
|
||||||
|
// 3. 自动探测 Windows:git-bash → busybox-w32 → 无
|
||||||
|
// POSIX :/bin/sh
|
||||||
|
// 4. env AGENT_SHELL_ARGS 覆盖参数模板(默认 -c,如 bash 想读 rc 可写 -lc)
|
||||||
|
// 另:env AGENT_GIT_BASH / AGENT_BUSYBOX 可指定各自的固定位置(便携安装用)。
|
||||||
|
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
const { spawn } = require('child_process');
|
||||||
|
|
||||||
|
const IS_WIN = process.platform === 'win32';
|
||||||
|
|
||||||
|
const INSTALL_HINT = IS_WIN
|
||||||
|
? 'Windows 需要 POSIX shell:装 Git for Windows(自带 bash),或把 busybox-w32 放到 local/bin/busybox.exe,'
|
||||||
|
+ '或用环境变量 AGENT_SHELL 指定 shell 路径'
|
||||||
|
: '需要 POSIX shell(/bin/sh 不存在)';
|
||||||
|
|
||||||
|
// MSYS(Git for Windows)默认会把「看起来像 Unix 路径」的参数改写成 Windows 路径
|
||||||
|
// (/c/foo → C:\foo)。模型的命令里 /tmp、/c、相对路径都可能被它悄悄改掉,
|
||||||
|
// 排查起来像"命令没生效"。关掉自动转换,让字节原样过去。
|
||||||
|
const MSYS_ENV = {
|
||||||
|
MSYS_NO_PATHCONV: '1', // Git for Windows 旧变量
|
||||||
|
MSYS2_ARG_CONV_EXCL: '*', // MSYS2 新变量
|
||||||
|
};
|
||||||
|
|
||||||
|
let cacheKey = null;
|
||||||
|
let cached; // 解析结果;null = 解析过但没有可用 shell
|
||||||
|
|
||||||
|
function trimStr(v) { return typeof v === 'string' ? v.trim() : ''; }
|
||||||
|
|
||||||
|
// 参数模板按 shell 习惯切成数组(支持引号),默认 ['-c']。
|
||||||
|
function splitArgs(s) {
|
||||||
|
const out = [];
|
||||||
|
let cur = '';
|
||||||
|
let quote = null;
|
||||||
|
for (const ch of String(s)) {
|
||||||
|
if (quote) { if (ch === quote) quote = null; else cur += ch; continue; }
|
||||||
|
if (ch === '"' || ch === "'") { quote = ch; continue; }
|
||||||
|
if (/\s/.test(ch)) { if (cur) { out.push(cur); cur = ''; } continue; }
|
||||||
|
cur += ch;
|
||||||
|
}
|
||||||
|
if (cur) out.push(cur);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function shellArgs() {
|
||||||
|
const custom = trimStr(process.env.AGENT_SHELL_ARGS);
|
||||||
|
return custom ? splitArgs(custom) : ['-c'];
|
||||||
|
}
|
||||||
|
|
||||||
|
function existsExec(p) {
|
||||||
|
try {
|
||||||
|
if (!fs.statSync(p).isFile()) return false;
|
||||||
|
if (!IS_WIN) fs.accessSync(p, fs.constants.X_OK);
|
||||||
|
return true;
|
||||||
|
} catch (_) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 自己遍历 PATH,不调 where.exe:少一次进程启动,也避开 where 的输出编码差异。
|
||||||
|
function whichWin(name) {
|
||||||
|
const exts = /\.\w+$/.test(name) ? [''] : ['', '.exe', '.cmd', '.bat'];
|
||||||
|
for (const dir of String(process.env.PATH || '').split(path.delimiter)) {
|
||||||
|
if (!dir) continue;
|
||||||
|
for (const ext of exts) {
|
||||||
|
const p = path.join(dir, name + ext);
|
||||||
|
if (existsExec(p)) return p;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Git for Windows 的 bash。C:\Windows\System32\bash.exe 是 WSL 启动器,明确排除:
|
||||||
|
// 它的 -c 之后是 Linux 命令,路径全在另一个文件系统里,拿它当 shell 会让每个命令都跑偏。
|
||||||
|
function findGitBash() {
|
||||||
|
const e = process.env;
|
||||||
|
const cands = [
|
||||||
|
e.AGENT_GIT_BASH,
|
||||||
|
e.ProgramFiles && path.join(e.ProgramFiles, 'Git', 'bin', 'bash.exe'),
|
||||||
|
e['ProgramFiles(x86)'] && path.join(e['ProgramFiles(x86)'], 'Git', 'bin', 'bash.exe'),
|
||||||
|
e.LOCALAPPDATA && path.join(e.LOCALAPPDATA, 'Programs', 'Git', 'bin', 'bash.exe'),
|
||||||
|
e.USERPROFILE && path.join(e.USERPROFILE, 'scoop', 'apps', 'git', 'current', 'bin', 'bash.exe'),
|
||||||
|
e.ProgramData && path.join(e.ProgramData, 'chocolatey', 'bin', 'bash.exe'),
|
||||||
|
whichWin('bash.exe'),
|
||||||
|
];
|
||||||
|
for (const c of cands) {
|
||||||
|
if (!c) continue;
|
||||||
|
if (/\\windows\\(system32|winsxs)\\/i.test(c) || /\\windowsapps\\/i.test(c)) continue;
|
||||||
|
if (existsExec(c)) return c;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// busybox-w32:单文件原生 exe(约 600KB),需要 `busybox sh -c` 的 applet 形式。
|
||||||
|
// 固定位置放在仓库 local/bin/,由启动器下载——不进系统 PATH,卸载即净。
|
||||||
|
function findBusybox() {
|
||||||
|
const e = process.env;
|
||||||
|
const cands = [
|
||||||
|
e.AGENT_BUSYBOX,
|
||||||
|
path.join(__dirname, '..', '..', 'local', 'bin', 'busybox.exe'),
|
||||||
|
whichWin('busybox.exe'),
|
||||||
|
];
|
||||||
|
for (const c of cands) {
|
||||||
|
if (c && existsExec(c)) return c;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function posixDefault() {
|
||||||
|
return { cmd: '/bin/sh', args: shellArgs(), kind: 'sh', source: 'default', env: null, detached: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
function fromExplicit(p) {
|
||||||
|
const args = shellArgs();
|
||||||
|
const busybox = /busybox/i.test(path.basename(p));
|
||||||
|
return {
|
||||||
|
cmd: p,
|
||||||
|
// busybox 是多 applet 单文件:必须点名 sh,否则 argv[0] 是 busybox 时它会当自己的子命令解析。
|
||||||
|
args: busybox ? ['sh', ...args] : args,
|
||||||
|
kind: busybox ? 'busybox' : 'bash',
|
||||||
|
source: 'explicit',
|
||||||
|
env: IS_WIN ? MSYS_ENV : null,
|
||||||
|
// POSIX 必须 detached(进程组是 killTree 的抓手);Windows 上开 detached 会新建控制台
|
||||||
|
// 并让子进程脱离 taskkill /T 的父子树,所以那边明确关掉。
|
||||||
|
detached: !IS_WIN,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function detectWindows() {
|
||||||
|
const bash = findGitBash();
|
||||||
|
if (bash) {
|
||||||
|
return { cmd: bash, args: shellArgs(), kind: 'bash', source: 'git-bash', env: MSYS_ENV, detached: false };
|
||||||
|
}
|
||||||
|
const bb = findBusybox();
|
||||||
|
if (bb) {
|
||||||
|
return { cmd: bb, args: ['sh', ...shellArgs()], kind: 'busybox', source: 'busybox-w32', env: null, detached: false };
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function detect(cfg) {
|
||||||
|
const explicit = trimStr(process.env.AGENT_SHELL)
|
||||||
|
|| trimStr(cfg && cfg.terminal && cfg.terminal.shell);
|
||||||
|
if (explicit) return fromExplicit(explicit);
|
||||||
|
if (!IS_WIN) return posixDefault();
|
||||||
|
return detectWindows();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 解析结果(对象形态,含 cmd/args/kind/source/env/detached)。没有可用 shell 时返回 null。
|
||||||
|
// 缓存键跟着「显式指定」的三个来源走:同一个进程里 cfg 或 env 变了会重新探测,
|
||||||
|
// 避免第一次调用(可能没有 cfg,比如技能层)把结果钉死。
|
||||||
|
function resolve(cfg) {
|
||||||
|
const key = [
|
||||||
|
trimStr(process.env.AGENT_SHELL),
|
||||||
|
trimStr(process.env.AGENT_SHELL_ARGS),
|
||||||
|
trimStr(cfg && cfg.terminal && cfg.terminal.shell),
|
||||||
|
].join('\u0000');
|
||||||
|
if (cacheKey !== key) {
|
||||||
|
cacheKey = key;
|
||||||
|
cached = detect(cfg);
|
||||||
|
}
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 重新探测(测试与「改完立即生效」用;正常运行不需要调)。
|
||||||
|
function reset() { cacheKey = null; cached = undefined; }
|
||||||
|
|
||||||
|
function spawnShell(cfg, command, opts) {
|
||||||
|
const o = opts || {};
|
||||||
|
const sh = resolve(cfg);
|
||||||
|
if (!sh) throw new Error('执行后端不可用:' + INSTALL_HINT);
|
||||||
|
const env = sh.env ? { ...process.env, ...sh.env, ...(o.env || {}) } : { ...process.env, ...(o.env || {}) };
|
||||||
|
return spawn(sh.cmd, [...sh.args, String(command)], {
|
||||||
|
cwd: o.cwd,
|
||||||
|
env,
|
||||||
|
detached: sh.detached,
|
||||||
|
// 仅 Windows 生效:detached 之外的第二道保险,避免每条命令弹一个控制台窗口。
|
||||||
|
windowsHide: true,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 杀整棵进程树。POSIX 走进程组(原来那两行原样保留);Windows 没有进程组,
|
||||||
|
// 用 taskkill /T 按父子树杀——不能用 child.kill(),那只会杀 shell 本身,
|
||||||
|
// 模型起的 node/python/ffmpeg 孙进程会留下来继续占端口。
|
||||||
|
function killTree(child) {
|
||||||
|
if (!child || !child.pid) return false;
|
||||||
|
if (!IS_WIN) {
|
||||||
|
try { process.kill(-child.pid, 'SIGKILL'); return true; } catch (_) {
|
||||||
|
try { child.kill('SIGKILL'); return true; } catch (__) { return false; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const p = spawn('taskkill', ['/T', '/F', '/PID', String(child.pid)], { stdio: 'ignore', windowsHide: true });
|
||||||
|
p.on('error', () => {});
|
||||||
|
p.unref();
|
||||||
|
return true;
|
||||||
|
} catch (_) {
|
||||||
|
try { child.kill(); return true; } catch (__) { return false; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 一行诊断(启动日志 / 健康检查用):告诉人「模型命令到底交给谁跑」。
|
||||||
|
function describe(cfg) {
|
||||||
|
const sh = resolve(cfg);
|
||||||
|
if (!sh) return '未找到(' + INSTALL_HINT + ')';
|
||||||
|
const args = sh.args.join(' ');
|
||||||
|
return sh.cmd + ' ' + args + ' ← ' + sh.source;
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { resolve, reset, spawnShell, killTree, describe, INSTALL_HINT };
|
||||||
@@ -198,6 +198,23 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"type": "function",
|
||||||
|
"function": {
|
||||||
|
"name": "profile",
|
||||||
|
"description": "Maintain the current user's profile — stable facts that persist across conversations and get injected into the context of NEW sessions (the current session's injected copy is frozen). Ops: list (read the live profile), set (honorific or industry, single short value), add (append preference tags), remove (delete exact preference tags). Rules: only record what the user has clearly stated or asked to be remembered (form of address, domain, stable output/work preferences); never guess personality, never store one-time task parameters; brief tags beat essays. Preference is a 、-separated tag list (each tag ≤15 chars, ≤24 tags, ≤300 chars total; overflow is rejected — consolidate or remove first). When unsure what is already recorded, op=list returns live state — trust it over memory.",
|
||||||
|
"parameters": {
|
||||||
|
"type": "object",
|
||||||
|
"required": ["op"],
|
||||||
|
"properties": {
|
||||||
|
"op": { "type": "string", "enum": ["list", "set", "add", "remove"], "description": "list = read live profile; set = single-value honorific/industry; add/remove = preference tags." },
|
||||||
|
"honorific": { "type": "string", "description": "op=set: how to address the user (≤20 chars, e.g. 王工). Pass empty string to clear. Exactly one of honorific/industry per call." },
|
||||||
|
"industry": { "type": "string", "description": "op=set: the user's industry/domain (≤20 chars, e.g. 金融). Pass empty string to clear." },
|
||||||
|
"tags": { "type": "array", "items": { "type": "string" }, "description": "op=add/remove: preference tag list, e.g. [\"偏好简洁回复\", \"图表中文标注\"]. Matching is exact text." }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"type": "function",
|
"type": "function",
|
||||||
"function": {
|
"function": {
|
||||||
@@ -323,17 +340,11 @@
|
|||||||
"description": "Run or inspect the skills installed on this server. Each skill describes its purpose and input_schema.\n\n{\"op\":\"list\"} list every skill with a one-line description\n{\"op\":\"get\",\"name\":\"<skill>\"} return the skill's full details; call it before the first run\n{\"op\":\"run\",\"name\":\"<skill>\",\"args\":{...}} execute it; args follow its input_schema\n\nop is required. op=get and op=run require name. Put skill arguments inside args, never at the top level.",
|
"description": "Run or inspect the skills installed on this server. Each skill describes its purpose and input_schema.\n\n{\"op\":\"list\"} list every skill with a one-line description\n{\"op\":\"get\",\"name\":\"<skill>\"} return the skill's full details; call it before the first run\n{\"op\":\"run\",\"name\":\"<skill>\",\"args\":{...}} execute it; args follow its input_schema\n\nop is required. op=get and op=run require name. Put skill arguments inside args, never at the top level.",
|
||||||
"parameters": {
|
"parameters": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"required": [
|
"required": ["op"],
|
||||||
"op"
|
|
||||||
],
|
|
||||||
"properties": {
|
"properties": {
|
||||||
"op": {
|
"op": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"enum": [
|
"enum": ["list", "get", "run"],
|
||||||
"list",
|
|
||||||
"get",
|
|
||||||
"run"
|
|
||||||
],
|
|
||||||
"description": "Operation to perform on skills."
|
"description": "Operation to perform on skills."
|
||||||
},
|
},
|
||||||
"name": {
|
"name": {
|
||||||
@@ -392,56 +403,6 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
|
||||||
"type": "function",
|
|
||||||
"function": {
|
|
||||||
"name": "device",
|
|
||||||
"description": "Operate the remote devices (other machines) connected to this server. Devices dial out to this server, so they need no inbound port; they stay connected until closed.\n\n- action=list: no other params. Returns every online device with os/arch/shell/root. Always call this first when you don't know device names.\n- action=health: requires device. Returns host uptime, load, memory, disk and temperature (fields the platform can't provide are -1).\n- action=exec: requires device and command. Runs the command through a shell on that device (sh -c on Unix, cmd /c on Windows) and returns stdout, stderr and the exit code. `cwd` must be inside that device's work root; omit it to use the root.\n\n- action=pull: requires device and remote_path; copies a file from the device into the session directory so read_file / skills can use it.\n- action=push: requires device, local_path and remote_path; sends a session file to the device.\n\nUse it when the work has to happen on the user's own machine (laptop, box, Windows PC). For the machine running this server use `terminal` instead. If a device is offline, say so explicitly — do not silently run the command elsewhere.",
|
|
||||||
"parameters": {
|
|
||||||
"type": "object",
|
|
||||||
"required": [
|
|
||||||
"action"
|
|
||||||
],
|
|
||||||
"properties": {
|
|
||||||
"action": {
|
|
||||||
"type": "string",
|
|
||||||
"enum": [
|
|
||||||
"list",
|
|
||||||
"health",
|
|
||||||
"exec",
|
|
||||||
"pull",
|
|
||||||
"push"
|
|
||||||
],
|
|
||||||
"description": "Operation to perform."
|
|
||||||
},
|
|
||||||
"device": {
|
|
||||||
"type": "string",
|
|
||||||
"description": "Device name from action=list."
|
|
||||||
},
|
|
||||||
"command": {
|
|
||||||
"type": "string",
|
|
||||||
"description": "Shell command line (action=exec). Avoid interactive commands."
|
|
||||||
},
|
|
||||||
"cwd": {
|
|
||||||
"type": "string",
|
|
||||||
"description": "Working directory on the device; must be inside its work root (action=exec)."
|
|
||||||
},
|
|
||||||
"timeout_ms": {
|
|
||||||
"type": "integer",
|
|
||||||
"description": "Default 120000, max 600000 (action=exec)."
|
|
||||||
},
|
|
||||||
"remote_path": {
|
|
||||||
"type": "string",
|
|
||||||
"description": "设备上的绝对路径,必须在设备工作根内(pull/push)。"
|
|
||||||
},
|
|
||||||
"local_path": {
|
|
||||||
"type": "string",
|
|
||||||
"description": "会话目录内的相对路径。pull 省略则用远端文件名;push 必填(源文件)。"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
"type": "function",
|
"type": "function",
|
||||||
"function": {
|
"function": {
|
||||||
|
|||||||
+42
-126
@@ -5,16 +5,15 @@ const path = require('path');
|
|||||||
const net = require('net'); // fetch SSRF 防护:IP 字面量/解析结果判私网
|
const net = require('net'); // fetch SSRF 防护:IP 字面量/解析结果判私网
|
||||||
const dns = require('dns').promises; // 同上:主机名 → IP 后统一判定
|
const dns = require('dns').promises; // 同上:主机名 → IP 后统一判定
|
||||||
const fsp = require('fs').promises;
|
const fsp = require('fs').promises;
|
||||||
const { spawn } = require('child_process');
|
const shell = require('../shell'); // 执行后端:shell 解析 + 进程树 kill(平台差异只在那边,这里不做分支)
|
||||||
const mcp = require('../mcp');
|
const mcp = require('../mcp');
|
||||||
const skills = require('./skills');
|
const skills = require('./skills');
|
||||||
const Database = require('better-sqlite3'); // db 工具:会话目录下的 data.db(同步 API,与单进程模型契合)
|
const Database = require('better-sqlite3'); // db 工具:会话目录下的 data.db(同步 API,与单进程模型契合)
|
||||||
const TurndownService = require('turndown'); // fetch 工具:HTML→Markdown 用真解析器(内置 htmlparser2,容错截断/畸形文档)
|
const TurndownService = require('turndown'); // fetch 工具:HTML→Markdown 用真解析器(内置 htmlparser2,容错截断/畸形文档)
|
||||||
const rexec = require('../remote-exec');
|
const rexec = require('../remote-exec');
|
||||||
const devices = require('../devices'); // device 工具:远端执行节点(设备主动出站连 core,见 devices.js)
|
|
||||||
const log = require('../log'); // device 工具调用日志(info 记动作+设备+耗时+命令截断)
|
|
||||||
const publicFiles = require('../public-files');
|
const publicFiles = require('../public-files');
|
||||||
const scheduler = require('../scheduler'); // 只依赖 log/cron-parser/time.js,不成环(engine→executor→scheduler 单向)
|
const scheduler = require('../scheduler'); // 只依赖 log/cron-parser/time.js,不成环(engine→executor→scheduler 单向)
|
||||||
|
const profile = require('../user-profile'); // profile 工具的数据面(仅 llm/log 依赖,无环)
|
||||||
const memory = require('../memory'); // recall 工具的数据面(日记翻阅;仅依赖 time.js,无环)
|
const memory = require('../memory'); // recall 工具的数据面(日记翻阅;仅依赖 time.js,无环)
|
||||||
// lab 的 help 伪工具要读全量定义:与 engine 同路径 require → node 缓存同一对象,单一事实源。
|
// lab 的 help 伪工具要读全量定义:与 engine 同路径 require → node 缓存同一对象,单一事实源。
|
||||||
const BUILTIN_TOOL_DEFS = require('./definitions.json');
|
const BUILTIN_TOOL_DEFS = require('./definitions.json');
|
||||||
@@ -765,7 +764,7 @@ function selectOutput(text, head, tail) {
|
|||||||
return parts.join('\n\n');
|
return parts.join('\n\n');
|
||||||
}
|
}
|
||||||
|
|
||||||
// terminal:spawn + 进程组 kill + 超时 + 输出截断
|
// terminal:交执行后端起 shell(POSIX 默认 /bin/sh -c,Windows 由 shell.js 探测)+ 超时 + 输出截断
|
||||||
// 通用终端输出 UI 卡片通道:命令行尾部的 ::ui_card {json}:: 标记行 → 从模型面剥离,整块交 ctx.onCard
|
// 通用终端输出 UI 卡片通道:命令行尾部的 ::ui_card {json}:: 标记行 → 从模型面剥离,整块交 ctx.onCard
|
||||||
// (与 MCP 回包 ui_card 块同一协议,见 mcp.js:任何命令行都可产卡,不限 officecli 封装层)。
|
// (与 MCP 回包 ui_card 块同一协议,见 mcp.js:任何命令行都可产卡,不限 officecli 封装层)。
|
||||||
// JSON 解析失败/无 action/ctx 不带 onCard 时标记行原样保留(宁可见不丢数据)。
|
// JSON 解析失败/无 action/ctx 不带 onCard 时标记行原样保留(宁可见不丢数据)。
|
||||||
@@ -785,116 +784,6 @@ function drainUiCards(text, ctx) {
|
|||||||
return keep.join('\n');
|
return keep.join('\n');
|
||||||
}
|
}
|
||||||
|
|
||||||
// device 工具:把命令送到远端设备执行(设备主动出站连 core,连接表在 devices.js)。
|
|
||||||
// 与 terminal 的分工:terminal 只在 core 所在机器/容器里跑,需要落在用户自己的电脑、盒子、
|
|
||||||
// Windows 上时用 device。设备不在线就明确报错,不自动降级到本机执行。
|
|
||||||
// device 日志用:命令压成一行并截断,避免长命令刷屏
|
|
||||||
function devCmd(s, n) {
|
|
||||||
const t = String(s || '').replace(/\s+/g, ' ').trim();
|
|
||||||
return t.length > (n || 120) ? t.slice(0, n || 120) + '…' : t;
|
|
||||||
}
|
|
||||||
|
|
||||||
// device 日志用:字节数human化
|
|
||||||
function devBytes(n) {
|
|
||||||
if (!n) return '0B';
|
|
||||||
if (n < 1024) return n + 'B';
|
|
||||||
if (n < 1024 * 1024) return (n / 1024).toFixed(1) + 'KB';
|
|
||||||
return (n / 1024 / 1024).toFixed(2) + 'MB';
|
|
||||||
}
|
|
||||||
|
|
||||||
async function toolDevice(ctx, args) {
|
|
||||||
if (!devices.enabled()) {
|
|
||||||
return '设备接入未启用:需要配置公网前缀(PUBLIC_BASE_URL 或设置页「公网地址」)和 DEVICE_TOKEN,重启 core 后生效。';
|
|
||||||
}
|
|
||||||
const action = String(args.action || '').trim();
|
|
||||||
|
|
||||||
if (action === 'list') {
|
|
||||||
const list = devices.list();
|
|
||||||
log.debug('device', 'list → ' + list.length + ' 台');
|
|
||||||
if (!list.length) return '当前没有设备在线(设备需主动连 wss://<公网前缀>/dev/ws)。';
|
|
||||||
return JSON.stringify(list, null, 2);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (action === 'health') {
|
|
||||||
const name = String(args.device || '').trim();
|
|
||||||
if (!name) return 'Error: action=health 需要 device 参数(先调 action=list 看设备名)';
|
|
||||||
try {
|
|
||||||
const h = await devices.health(name);
|
|
||||||
log.debug('device', 'health ' + name + ' ok');
|
|
||||||
return JSON.stringify(h, null, 2);
|
|
||||||
} catch (e) {
|
|
||||||
log.warn('device', 'health ' + name + ' 失败:' + e.message);
|
|
||||||
return 'Error: ' + e.message;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (action === 'exec') {
|
|
||||||
const name = String(args.device || '').trim();
|
|
||||||
if (!name) return 'Error: action=exec 需要 device 参数(先调 action=list 看设备名)';
|
|
||||||
if (!String(args.command || '').trim()) return 'Error: action=exec 需要 command 参数';
|
|
||||||
try {
|
|
||||||
const r = await devices.exec({
|
|
||||||
device: name,
|
|
||||||
command: args.command,
|
|
||||||
cwd: args.cwd,
|
|
||||||
timeout_ms: args.timeout_ms,
|
|
||||||
});
|
|
||||||
log.info('device', `exec ${r.device} code=${r.code} ${r.ms}ms cmd="${devCmd(args.command)}"`);
|
|
||||||
const head = `device=${r.device} exit=${r.code}`
|
|
||||||
+ (r.killed_by ? ` killed_by=${r.killed_by}` : '')
|
|
||||||
+ ` ${r.ms}ms` + (r.truncated ? '(输出已截断)' : '');
|
|
||||||
const parts = [head];
|
|
||||||
if (r.note) parts.push('note: ' + r.note);
|
|
||||||
if (r.stdout && r.stdout.trim()) parts.push('--- stdout ---\n' + r.stdout.replace(/\s+$/, ''));
|
|
||||||
if (r.stderr && r.stderr.trim()) parts.push('--- stderr ---\n' + r.stderr.replace(/\s+$/, ''));
|
|
||||||
return parts.join('\n');
|
|
||||||
} catch (e) {
|
|
||||||
log.warn('device', `exec ${name} 失败:${e.message} cmd="${devCmd(args.command)}"`);
|
|
||||||
return 'Error: ' + e.message;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (action === 'pull') {
|
|
||||||
const name = String(args.device || '').trim();
|
|
||||||
const remote = String(args.remote_path || '').trim();
|
|
||||||
if (!name) return 'Error: action=pull 需要 device 参数(先调 action=list 看设备名)';
|
|
||||||
if (!remote) return 'Error: action=pull 需要 remote_path 参数';
|
|
||||||
try {
|
|
||||||
const rel = String(args.local_path || '').trim() || path.basename(remote);
|
|
||||||
const abs = resolveInTask(ctx.taskDir, rel, fsRoot(ctx));
|
|
||||||
const t0 = Date.now();
|
|
||||||
const r = await devices.pull({ device: name, remotePath: remote, localPath: abs });
|
|
||||||
recordFile(ctx, abs);
|
|
||||||
log.info('device', `pull ${name} ${remote} → ${path.relative(ctx.taskDir, abs) || path.basename(abs)} ${devBytes(r.bytes)} ${Date.now() - t0}ms`);
|
|
||||||
return `已拉到 ${path.relative(ctx.taskDir, abs) || path.basename(abs)}(${r.bytes} 字节,sha256 ${r.sha256.slice(0, 16)}…)`;
|
|
||||||
} catch (e) {
|
|
||||||
log.warn('device', `pull ${name} ${remote} 失败:${e.message}`);
|
|
||||||
return 'Error: ' + e.message;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (action === 'push') {
|
|
||||||
const name = String(args.device || '').trim();
|
|
||||||
const local = String(args.local_path || '').trim();
|
|
||||||
const remote = String(args.remote_path || '').trim();
|
|
||||||
if (!name) return 'Error: action=push 需要 device 参数(先调 action=list 看设备名)';
|
|
||||||
if (!local) return 'Error: action=push 需要 local_path 参数(会话目录内的相对路径)';
|
|
||||||
if (!remote) return 'Error: action=push 需要 remote_path 参数(设备上的绝对路径,须在工作根内)';
|
|
||||||
try {
|
|
||||||
const abs = resolveInTask(ctx.taskDir, local, fsRoot(ctx));
|
|
||||||
const t0 = Date.now();
|
|
||||||
const r = await devices.push({ device: name, localPath: abs, remotePath: remote });
|
|
||||||
log.info('device', `push ${name} ${remote} ← ${path.relative(ctx.taskDir, abs) || path.basename(abs)} ${devBytes(r.bytes)} ${Date.now() - t0}ms`);
|
|
||||||
return `已推到 ${name}:${remote}(${r.bytes} 字节,sha256 ${r.sha256.slice(0, 16)}…)`;
|
|
||||||
} catch (e) {
|
|
||||||
log.warn('device', `push ${name} ${remote} 失败:${e.message}`);
|
|
||||||
return 'Error: ' + e.message;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return 'Error: action 必须是 list / health / exec / pull / push';
|
|
||||||
}
|
|
||||||
|
|
||||||
async function toolTerminal(ctx, args) {
|
async function toolTerminal(ctx, args) {
|
||||||
const cfg = ctx.cfg;
|
const cfg = ctx.cfg;
|
||||||
const timeout = args.timeout_ms || cfg.terminal.default_timeout_ms;
|
const timeout = args.timeout_ms || cfg.terminal.default_timeout_ms;
|
||||||
@@ -905,7 +794,7 @@ async function toolTerminal(ctx, args) {
|
|||||||
|
|
||||||
// 配了 executor.url(或 env EXECUTOR_URL):命令交给远端 agent-executor 执行,文本拼回与本地完全一致。
|
// 配了 executor.url(或 env EXECUTOR_URL):命令交给远端 agent-executor 执行,文本拼回与本地完全一致。
|
||||||
if (rexec.isRemote(cfg)) {
|
if (rexec.isRemote(cfg)) {
|
||||||
const r = await rexec.run(cfg, { command: args.command, cwd, timeout_ms: timeout, run: ctx.run, onChunk: ctx.onOutput });
|
const r = await rexec.run(cfg, { command: args.command, cwd, timeout_ms: timeout, run: ctx.run });
|
||||||
r.out = drainUiCards(r.out, ctx);
|
r.out = drainUiCards(r.out, ctx);
|
||||||
let text = selectOutput(r.out.replace(/\n+$/, ''), args.head_lines, args.tail_lines);
|
let text = selectOutput(r.out.replace(/\n+$/, ''), args.head_lines, args.tail_lines);
|
||||||
if (r.killed_by === 'timeout') {
|
if (r.killed_by === 'timeout') {
|
||||||
@@ -920,7 +809,7 @@ async function toolTerminal(ctx, args) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return new Promise((resolve) => {
|
return new Promise((resolve) => {
|
||||||
const child = spawn('/bin/sh', ['-c', args.command], { cwd, detached: true, env: process.env });
|
const child = shell.spawnShell(cfg, args.command, { cwd });
|
||||||
ctx.run.procs.add(child);
|
ctx.run.procs.add(child);
|
||||||
let out = '';
|
let out = '';
|
||||||
let killedBy = null; // 'timeout' | 'cancelled'
|
let killedBy = null; // 'timeout' | 'cancelled'
|
||||||
@@ -931,11 +820,7 @@ async function toolTerminal(ctx, args) {
|
|||||||
killGroup(child);
|
killGroup(child);
|
||||||
}, timeout);
|
}, timeout);
|
||||||
|
|
||||||
const onData = (d) => {
|
const onData = (d) => { out += d.toString(); };
|
||||||
const s = d.toString();
|
|
||||||
out += s;
|
|
||||||
if (ctx.onOutput) { try { ctx.onOutput(s); } catch (_) {} }
|
|
||||||
};
|
|
||||||
child.stdout.on('data', onData);
|
child.stdout.on('data', onData);
|
||||||
child.stderr.on('data', onData);
|
child.stderr.on('data', onData);
|
||||||
|
|
||||||
@@ -968,10 +853,8 @@ async function toolTerminal(ctx, args) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function killGroup(child) {
|
function killGroup(child) {
|
||||||
if (!child.pid) return;
|
// 平台差异交给执行后端:POSIX 杀进程组,Windows 走 taskkill /T 杀进程树。
|
||||||
try { process.kill(-child.pid, 'SIGKILL'); } catch (_) {
|
shell.killTree(child);
|
||||||
try { child.kill('SIGKILL'); } catch (__) {}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// fetch:抓取并转 Markdown。超时/取消覆盖到 body 读取完成(非仅响应头);
|
// fetch:抓取并转 Markdown。超时/取消覆盖到 body 读取完成(非仅响应头);
|
||||||
@@ -1461,6 +1344,39 @@ function toolScheduleTask(ctx, args) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// profile:用户画像增量维护(op 分派同 schedule 风格)。user 取自会话行,AI 不可指定他人;
|
||||||
|
// 条件必填/帽子校验全在 user-profile.js(抛错由引擎包成 is_error 回执),停用拒写不拒读。
|
||||||
|
function toolProfile(ctx, args) {
|
||||||
|
const op = String(args.op || '').trim().toLowerCase();
|
||||||
|
const s = ctx.db.prepare('SELECT user FROM sessions WHERE id = ?').get(ctx.sessionId);
|
||||||
|
if (!s) throw new Error('会话不存在');
|
||||||
|
const user = s.user;
|
||||||
|
switch (op) {
|
||||||
|
case 'list': {
|
||||||
|
const p = profile.getProfile(ctx.db, user);
|
||||||
|
const lines = [
|
||||||
|
'称谓:' + (p.honorific || '(未记录)'),
|
||||||
|
'行业:' + (p.industry || '(未记录)'),
|
||||||
|
'偏好:' + (p.preference || '(未记录)'),
|
||||||
|
];
|
||||||
|
if (!p.enabled) lines.push('(该用户已停用画像注入;set/add/remove 会被拒绝)');
|
||||||
|
lines.push('本会话已注入的快照不会因写入而变;新会话自动携带最新画像。');
|
||||||
|
return lines.join('\n');
|
||||||
|
}
|
||||||
|
case 'set': {
|
||||||
|
const keys = ['honorific', 'industry'].filter(k => typeof args[k] === 'string');
|
||||||
|
if (keys.length !== 1) throw new Error('op=set 需要 honorific 或 industry 恰一个字符串参数(偏好标签用 add/remove)');
|
||||||
|
return profile.setProfileField(ctx.db, user, keys[0], args[keys[0]]);
|
||||||
|
}
|
||||||
|
case 'add':
|
||||||
|
return profile.addProfileTags(ctx.db, user, args.tags);
|
||||||
|
case 'remove':
|
||||||
|
return profile.removeProfileTags(ctx.db, user, args.tags);
|
||||||
|
default:
|
||||||
|
throw new Error('未知的 op:"' + op + '"。可用:list / set(honorific|industry) / add(tags) / remove(tags)');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// db:会话本地 SQLite(taskDir/data.db,随会话目录隔离,首次使用自动建库建文件)。
|
// db:会话本地 SQLite(taskDir/data.db,随会话目录隔离,首次使用自动建库建文件)。
|
||||||
// 连接策略:每次调用 open→用→close,不缓存句柄(会话删目录后不留脏连接);
|
// 连接策略:每次调用 open→用→close,不缓存句柄(会话删目录后不留脏连接);
|
||||||
// 单进程 + better-sqlite3 同步 API,同进程内不存在交叠。busy_timeout 兼容
|
// 单进程 + better-sqlite3 同步 API,同进程内不存在交叠。busy_timeout 兼容
|
||||||
@@ -1868,9 +1784,9 @@ const HANDLERS = {
|
|||||||
terminal: toolTerminal,
|
terminal: toolTerminal,
|
||||||
fetch: toolFetch,
|
fetch: toolFetch,
|
||||||
schedule: toolScheduleTask,
|
schedule: toolScheduleTask,
|
||||||
|
profile: toolProfile,
|
||||||
recall: toolRecall,
|
recall: toolRecall,
|
||||||
db: toolDb,
|
db: toolDb,
|
||||||
device: toolDevice,
|
|
||||||
skill: toolSkill,
|
skill: toolSkill,
|
||||||
lab: toolLab,
|
lab: toolLab,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ const { spawn } = require('child_process');
|
|||||||
const YAML = require('yaml');
|
const YAML = require('yaml');
|
||||||
const log = require('../log');
|
const log = require('../log');
|
||||||
const rexec = require('../remote-exec');
|
const rexec = require('../remote-exec');
|
||||||
|
const shell = require('../shell'); // 本地 spawn 技能时的进程树 kill(平台差异只在 shell.js)
|
||||||
// mode=skill 的 MCP 工具在 get/run 时由 core 直接转发;mcp.js 只依赖 ./log,不成环。
|
// mode=skill 的 MCP 工具在 get/run 时由 core 直接转发;mcp.js 只依赖 ./log,不成环。
|
||||||
const mcp = require('../mcp');
|
const mcp = require('../mcp');
|
||||||
|
|
||||||
@@ -187,7 +188,8 @@ function runEntry(ctx, entry, args, cwd, timeoutMs) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
const child = spawn(entry, args, { cwd, env: process.env, detached: true });
|
// windowsHide:Windows 上 detached 之外的第二道保险,避免弹控制台;POSIX 忽略该选项。
|
||||||
|
const child = spawn(entry, args, { cwd, env: process.env, detached: true, windowsHide: true });
|
||||||
if (ctx.run && ctx.run.procs) ctx.run.procs.add(child);
|
if (ctx.run && ctx.run.procs) ctx.run.procs.add(child);
|
||||||
let out = '';
|
let out = '';
|
||||||
let settled = false;
|
let settled = false;
|
||||||
@@ -200,7 +202,7 @@ function runEntry(ctx, entry, args, cwd, timeoutMs) {
|
|||||||
settled = true;
|
settled = true;
|
||||||
clearInterval(cancelCheck);
|
clearInterval(cancelCheck);
|
||||||
if (ctx.run && ctx.run.procs) ctx.run.procs.delete(child);
|
if (ctx.run && ctx.run.procs) ctx.run.procs.delete(child);
|
||||||
try { process.kill(-child.pid, 'SIGKILL'); } catch (_) { try { child.kill('SIGKILL'); } catch (__) {} }
|
shell.killTree(child);
|
||||||
reject(new SkillExecutionError('技能执行超时(' + timeoutMs + 'ms)已终止:\n' + out.trim(), -1));
|
reject(new SkillExecutionError('技能执行超时(' + timeoutMs + 'ms)已终止:\n' + out.trim(), -1));
|
||||||
}, timeoutMs);
|
}, timeoutMs);
|
||||||
|
|
||||||
@@ -209,7 +211,7 @@ function runEntry(ctx, entry, args, cwd, timeoutMs) {
|
|||||||
settled = true;
|
settled = true;
|
||||||
clearTimeout(timer);
|
clearTimeout(timer);
|
||||||
if (ctx.run && ctx.run.procs) ctx.run.procs.delete(child);
|
if (ctx.run && ctx.run.procs) ctx.run.procs.delete(child);
|
||||||
try { process.kill(-child.pid, 'SIGKILL'); } catch (_) { try { child.kill('SIGKILL'); } catch (__) {} }
|
shell.killTree(child);
|
||||||
reject(new SkillExecutionError('技能执行被用户终止', -1));
|
reject(new SkillExecutionError('技能执行被用户终止', -1));
|
||||||
}
|
}
|
||||||
}, 200);
|
}, 200);
|
||||||
|
|||||||
@@ -7,15 +7,19 @@
|
|||||||
// - 注入:会话创建/清空时把渲染文本冻结进 sessions.profile_snapshot,
|
// - 注入:会话创建/清空时把渲染文本冻结进 sessions.profile_snapshot,
|
||||||
// buildMessages 每轮以 system 后首条 user 消息注入——内容字节恒定不破坏前缀缓存,
|
// buildMessages 每轮以 system 后首条 user 消息注入——内容字节恒定不破坏前缀缓存,
|
||||||
// 且不落 messages 表,阶段切换归档/压缩都动不到它。
|
// 且不落 messages 表,阶段切换归档/压缩都动不到它。
|
||||||
// - 更新:只由用户在设置页手动编辑。原 AI 侧的 profile 工具(list/set/add/remove)已移除:
|
// - 更新(原 handoff 落槌一次性提取链路已移除):AI 沟通中经 profile 工具增量维护
|
||||||
// 模型自主记录容易把错的东西冻结成长期上下文,记什么由用户把关。
|
// (list/set/add/remove,见 executor.js;写入只影响下个会话——快照冻结语义不变),
|
||||||
// - preference 是用户自由输入的多行文本(一行一条即可):原样入库、原样注入,不拆不拼、
|
// 用户也可在设置页手动编辑。preference 按顿号标签列表管理,工具只做增量增删、
|
||||||
// 不把分隔符规范化;只卡一个总长帽(PREF_MAX)。
|
// 不做整段覆写——防模型重写时吃掉旧标签;停用(enabled=0)时拒写不拒读。
|
||||||
const log = require('./log');
|
const log = require('./log');
|
||||||
|
|
||||||
const FIELDS = ['honorific', 'industry', 'preference'];
|
const FIELDS = ['honorific', 'industry', 'preference'];
|
||||||
const MAX_FIELD = 80; // honorific/industry 长度帽
|
const MAX_FIELD = 80; // honorific/industry 长度帽(Web 手改与工具共用)
|
||||||
const PREF_MAX = 1000; // preference 总长帽(用户自由输入的多行文本,只卡总量)
|
const PREF_MAX = 300; // preference 总长帽
|
||||||
|
const SET_MAX = 20; // AI 写 honorific/industry 的单值帽(称谓应当短小)
|
||||||
|
const TAG_MAX = 15; // 单个偏好标签长度帽
|
||||||
|
const TAGS_MAX = 24; // 偏好标签数量帽
|
||||||
|
const TAG_SPLIT = /[、,,;;\n]+/;
|
||||||
// 画像快照头:AI 友好的分块标记(与 channel_note/memory_note 同款「# [CTX] <名>」体例,
|
// 画像快照头:AI 友好的分块标记(与 channel_note/memory_note 同款「# [CTX] <名>」体例,
|
||||||
// buildMessages 把快照作 system 后首条 user 注入,标题即自描述来源)。
|
// buildMessages 把快照作 system 后首条 user 注入,标题即自描述来源)。
|
||||||
const SNAPSHOT_HEAD = '# [CTX] user_profile\n\n以下为历史会话沉淀的粗粒度认知,非任务约束;与当前请求冲突时,一律以当前请求为准。';
|
const SNAPSHOT_HEAD = '# [CTX] user_profile\n\n以下为历史会话沉淀的粗粒度认知,非任务约束;与当前请求冲突时,一律以当前请求为准。';
|
||||||
@@ -50,9 +54,7 @@ function sanitizePatch(body) {
|
|||||||
const patch = { fields: {}, enabled: undefined };
|
const patch = { fields: {}, enabled: undefined };
|
||||||
for (const k of FIELDS) {
|
for (const k of FIELDS) {
|
||||||
if (typeof b[k] === 'string') {
|
if (typeof b[k] === 'string') {
|
||||||
// preference 是用户按条目输入的自由文本:保留换行,只去首尾空白;另两字段压成单行
|
patch.fields[k] = b[k].replace(/\s+/g, ' ').trim().slice(0, k === 'preference' ? PREF_MAX : MAX_FIELD);
|
||||||
const v = k === 'preference' ? b[k].trim() : b[k].replace(/\s+/g, ' ').trim();
|
|
||||||
patch.fields[k] = v.slice(0, k === 'preference' ? PREF_MAX : MAX_FIELD);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (typeof b.enabled === 'boolean' || b.enabled === 0 || b.enabled === 1) patch.enabled = !!b.enabled;
|
if (typeof b.enabled === 'boolean' || b.enabled === 0 || b.enabled === 1) patch.enabled = !!b.enabled;
|
||||||
@@ -68,6 +70,77 @@ function saveProfile(db, user, patch) {
|
|||||||
writeRow(db, user, data, enabled);
|
writeRow(db, user, data, enabled);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---------- profile 工具(AI 增量维护入口;op 语义与 executor.js toolProfile 对应) ----------
|
||||||
|
// preference 存顿号连接的标签串;读取按分隔符拆 token(人工输入的整句会被拆为 token 存留,可接受)。
|
||||||
|
function profileTokens(preference) {
|
||||||
|
return String(preference || '').split(TAG_SPLIT).map(t => t.trim()).filter(Boolean);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 所有写 op 的统一后缀:快照「新会话冻结注入」语义不因工具改变,明说免 AI 在本会话里困惑等待。
|
||||||
|
const WRITE_NOTE = '(新会话开始时注入,本会话内不变;可用 op=list 查看实时状态)';
|
||||||
|
|
||||||
|
function requireEnabled(db, user) {
|
||||||
|
if (!getProfile(db, user).enabled) {
|
||||||
|
throw new Error('该用户已停用画像(设置页·账户·用户画像可重新启用),本次未写入。');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 单值字段(称谓/行业)设置;空串 = 清除。
|
||||||
|
function setProfileField(db, user, field, value) {
|
||||||
|
if (!FIELDS.includes(field) || field === 'preference') {
|
||||||
|
throw new Error('op=set 仅支持 honorific / industry(偏好标签请用 op=add / op=remove)');
|
||||||
|
}
|
||||||
|
requireEnabled(db, user);
|
||||||
|
const v = String(value == null ? '' : value).replace(/\s+/g, ' ').trim().slice(0, SET_MAX);
|
||||||
|
const cur = getProfile(db, user)[field];
|
||||||
|
if (cur === v) return FIELD_LABELS[field] + '已是「' + v + '」,未改动。';
|
||||||
|
saveProfile(db, user, { fields: { [field]: v } });
|
||||||
|
return v
|
||||||
|
? FIELD_LABELS[field] + '已设为「' + v + '」' + WRITE_NOTE
|
||||||
|
: FIELD_LABELS[field] + '已清除(下次冻结时将不再出现)。';
|
||||||
|
}
|
||||||
|
|
||||||
|
// 追加偏好标签:清洗 → 逐条校验长度 → 去重 → 数量/总长帽(整批原子:任一带帽违例则不落库)
|
||||||
|
function addProfileTags(db, user, tags) {
|
||||||
|
const list = (Array.isArray(tags) ? tags : [tags])
|
||||||
|
.map(t => String(t == null ? '' : t).replace(TAG_SPLIT, ' ').replace(/\s+/g, ' ').trim())
|
||||||
|
.filter(Boolean);
|
||||||
|
if (!list.length) throw new Error('op=add 需要非空的 tags 字符串数组(单个标签也用数组传)');
|
||||||
|
requireEnabled(db, user);
|
||||||
|
const cur = profileTokens(getProfile(db, user).preference);
|
||||||
|
const added = [], dup = [];
|
||||||
|
for (const t of list) {
|
||||||
|
if (t.length > TAG_MAX) throw new Error('标签「' + t + '」超过 ' + TAG_MAX + ' 字上限,请换成更概括的说法');
|
||||||
|
if (cur.includes(t)) { dup.push(t); continue; }
|
||||||
|
cur.push(t); added.push(t);
|
||||||
|
}
|
||||||
|
if (cur.length > TAGS_MAX) throw new Error('偏好标签已达 ' + TAGS_MAX + ' 个上限(本次将到 ' + cur.length + '),先用 op=remove 合并精简');
|
||||||
|
const joined = cur.join('、');
|
||||||
|
if (joined.length > PREF_MAX) throw new Error('偏好总长将超 ' + PREF_MAX + ' 字(现 ' + joined.length + '),先用 op=remove 精简');
|
||||||
|
if (!added.length) {
|
||||||
|
return '均已存在,未新增(' + dup.join('、') + ');当前偏好 ' + cur.length + ' 条。';
|
||||||
|
}
|
||||||
|
saveProfile(db, user, { fields: { preference: joined } });
|
||||||
|
return '已记录:' + added.join('、')
|
||||||
|
+ (dup.length ? '(已存在未重复:' + dup.join('、') + ')' : '')
|
||||||
|
+ ';偏好现共 ' + cur.length + ' 条' + WRITE_NOTE;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 删除偏好标签:按 token 精确匹配;未命中的回报(引导先 list 核对写法)。
|
||||||
|
function removeProfileTags(db, user, tags) {
|
||||||
|
const list = (Array.isArray(tags) ? tags : [tags]).map(t => String(t == null ? '' : t).trim()).filter(Boolean);
|
||||||
|
if (!list.length) throw new Error('op=remove 需要非空的 tags 字符串数组');
|
||||||
|
requireEnabled(db, user);
|
||||||
|
const cur = profileTokens(getProfile(db, user).preference);
|
||||||
|
const removed = list.filter(t => cur.includes(t));
|
||||||
|
const missing = list.filter(t => !cur.includes(t));
|
||||||
|
if (!removed.length) return '未找到要删除的标签:' + missing.join('、') + '(op=list 可查看当前精确标签)';
|
||||||
|
saveProfile(db, user, { fields: { preference: cur.filter(t => !removed.includes(t)).join('、') } });
|
||||||
|
return '已移除:' + removed.join('、')
|
||||||
|
+ (missing.length ? ';未找到:' + missing.join('、') : '')
|
||||||
|
+ ';偏好现共 ' + (cur.length - removed.length) + ' 条' + WRITE_NOTE;
|
||||||
|
}
|
||||||
|
|
||||||
// 渲染注入文本:三字段(非空才成行);停用或全空 → 空串(不注入)。
|
// 渲染注入文本:三字段(非空才成行);停用或全空 → 空串(不注入)。
|
||||||
function snapshotText(db, user) {
|
function snapshotText(db, user) {
|
||||||
const p = getProfile(db, user);
|
const p = getProfile(db, user);
|
||||||
@@ -88,4 +161,5 @@ function freezeSnapshot(db, sessionId) {
|
|||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
getProfile, sanitizePatch, saveProfile, snapshotText, freezeSnapshot,
|
getProfile, sanitizePatch, saveProfile, snapshotText, freezeSnapshot,
|
||||||
|
setProfileField, addProfileTags, removeProfileTags,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -489,7 +489,7 @@ function getTurn(bid) { return turnState.get(bid) || resetTurn(bid); }
|
|||||||
|
|
||||||
// 投递前的内容归一(语义同旧 deliverNow):errAck / 空文本 → 不可投;富文本 blocks → 占位文案。
|
// 投递前的内容归一(语义同旧 deliverNow):errAck / 空文本 → 不可投;富文本 blocks → 占位文案。
|
||||||
function normalizeContent(m) {
|
function normalizeContent(m) {
|
||||||
if (!m || m.type === 'errAck' || m.type === 'error_note') return '';
|
if (!m || m.type === 'errAck') return '';
|
||||||
let content = String(m.content || '').trim();
|
let content = String(m.content || '').trim();
|
||||||
if (!content) return '';
|
if (!content) return '';
|
||||||
if (content.startsWith('{"__blocks__"')) content = '【富文本消息,请到网页端查看】';
|
if (content.startsWith('{"__blocks__"')) content = '【富文本消息,请到网页端查看】';
|
||||||
|
|||||||
@@ -1,140 +0,0 @@
|
|||||||
# agent-device:远端设备执行端
|
|
||||||
|
|
||||||
把一台机器(Linux 盒子、Windows、macOS)变成 agent 的一双“手”:**主动出站**连到 core 的
|
|
||||||
WebSocket 端点,接收 shell 命令、流式回传输出与退出码、上报主机指标。
|
|
||||||
|
|
||||||
设备不需要公网 IP、不需要开任何入站端口,NAT、公司网络、随身热点都能用。
|
|
||||||
|
|
||||||
> 这不是通用 agent,只是执行端。会话、模型、记忆都在服务端;这里只负责“在那台机器上跑东西”。
|
|
||||||
|
|
||||||
## 二进制里没有服务器地址
|
|
||||||
|
|
||||||
`-server` 与 token 都**没有默认值**,不显式给就启动失败。所以拿到的二进制不会连到别人的服务器上——
|
|
||||||
它只连你指定的那一台。
|
|
||||||
|
|
||||||
## 安装
|
|
||||||
|
|
||||||
### 自己编译
|
|
||||||
|
|
||||||
需要 Go 1.22+:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
git clone <本仓库> && cd device
|
|
||||||
go build -trimpath -ldflags "-s -w" -o bin/agent-device ./cmd/agent
|
|
||||||
```
|
|
||||||
|
|
||||||
交叉编译(一次出六个平台):
|
|
||||||
|
|
||||||
```sh
|
|
||||||
sh scripts/build.sh all
|
|
||||||
```
|
|
||||||
|
|
||||||
脚本只做构建:不联网、不推送、不依赖任何特定服务器。本机没有 Go 但装了 docker 时,
|
|
||||||
会自动用 `golang:1.23-alpine` 容器编译。
|
|
||||||
|
|
||||||
### 下载预编译
|
|
||||||
|
|
||||||
从本仓库的 Releases 页面取对应平台的文件(`agent-device-linux-arm64`、`agent-device-windows-amd64.exe` 等),
|
|
||||||
`chmod +x` 即可,静态链接、无运行时依赖,一个文件约 5.5 MB。
|
|
||||||
|
|
||||||
## 运行
|
|
||||||
|
|
||||||
```sh
|
|
||||||
# 推荐:二进制旁边放一个 config.json,直接启动(token 不出现在 ps 里)
|
|
||||||
./agent-device
|
|
||||||
|
|
||||||
# 或者全走命令行
|
|
||||||
./agent-device -server wss://your-host.example/dev/ws -token <TOKEN> -root /var/agent-work -name box-01
|
|
||||||
|
|
||||||
# 配置文件不在默认位置时显式指定
|
|
||||||
./agent-device -config /etc/agent-device.json
|
|
||||||
```
|
|
||||||
|
|
||||||
**默认会自动读可执行文件同目录的 `config.json`**(存在才读,不存在就当没配),所以部署时把二进制和配置放一个目录、直接跑就行:
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"server": "wss://your-host.example/dev/ws",
|
|
||||||
"token": "…",
|
|
||||||
"root": "/var/agent-work",
|
|
||||||
"name": "box-01"
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
优先级:**命令行显式参数 > 环境变量 `NODE_TOKEN`(仅 token)> 配置文件 > 默认值**。
|
|
||||||
|
|
||||||
### shell 用哪个
|
|
||||||
|
|
||||||
默认:macOS / Linux 用 `/bin/sh`(固定,不读 `$SHELL`——用户把默认 shell 设成 fish 时,
|
|
||||||
模型写的 POSIX 语法会全废);Windows 用 `cmd`。
|
|
||||||
|
|
||||||
想换就在 `config.json` 里写 `shell`,**不做自动探测**:装了 Git Bash / busybox 就写路径,
|
|
||||||
没装就保持默认。
|
|
||||||
|
|
||||||
```json
|
|
||||||
{ "shell": "C:\\Program Files\\Git\\bin\\bash.exe" }
|
|
||||||
```
|
|
||||||
|
|
||||||
报给 core 的是短标签(`sh` / `bash` / `busybox` / `cmd` / `powershell`),同时带上解释器路径与版本。
|
|
||||||
|
|
||||||
| 参数 | 说明 |
|
|
||||||
|---|---|
|
|
||||||
| `-server` | core 的接入地址,`wss://…/dev/ws` |
|
|
||||||
| `-token` | Bearer token,须与服务端 `DEVICE_TOKEN` 一致 |
|
|
||||||
| `-root` | 工作根目录,命令的 `cwd` 必须落在它之内(默认 `~/agent-work`,会自动建)。写相对路径时按**二进制所在目录**解析,如 `workspace` / `.`,不能越出该目录 |
|
|
||||||
| `-name` | 设备名,服务端用它区分设备(默认 hostname) |
|
|
||||||
| `-shell` | `sh` / `cmd` / `powershell`,默认按平台 |
|
|
||||||
| `-config` | 配置文件路径,默认 `<二进制所在目录>/config.json` |
|
|
||||||
| `-insecure` | 跳过证书校验(自签证书调试用) |
|
|
||||||
| `-fix-clock` | 证书报错时用服务器 `Date` 头校准本机时间(小设备没有 RTC 时用,Linux 需 root) |
|
|
||||||
|
|
||||||
设备名重复时后接入的会顶掉前一个连接(换机、重装不留僵尸连接)。
|
|
||||||
|
|
||||||
## 协议
|
|
||||||
|
|
||||||
一条 WebSocket 上全是 JSON 文本帧,`t` 区分类型:
|
|
||||||
|
|
||||||
| 方向 | 消息 |
|
|
||||||
|---|---|
|
|
||||||
| 设备 → core | `{t:"hello", ver, name, os, arch, shell, shell_path, shell_ver, root}` |
|
|
||||||
| core → 设备 | `{t:"exec", id, cmd, cwd, timeout_ms}` · `{t:"kill", id}` · `{t:"ping"}` · `{t:"health", id}` |
|
|
||||||
| 文件通道 | `{t:"file", id, op:"read"\|"write", path, size?, sha256?}` · `{t:"file.chunk", id, data:<base64>}` ×N · `{t:"file.done", id, size?, sha256?, err?}` |
|
|
||||||
| 设备 → core | `{t:"chunk", id, out:"out"\|"err", chunk:<base64>}` · `{t:"exit", id, code, killed_by, ms, truncated}` · `{t:"pong"}` · `{t:"health", …}` |
|
|
||||||
|
|
||||||
- 保活:core 每 20 秒发 `ping`,设备回 `pong`;90 秒无任何消息即断开重连。
|
|
||||||
- 断线:指数退避 1s → 2s → 4s → … 上限 30s,连上后重置。
|
|
||||||
- 超时:命令超过 `timeout_ms` 由设备侧杀**进程组**,回 `killed_by:"timeout"`。
|
|
||||||
- 输出:单流超过上限截断并置 `truncated`。
|
|
||||||
- `shell` 报的是实际解释器(`/bin/sh` 可能是 dash / bash / busybox),连同版本,供模型决定命令语法。
|
|
||||||
|
|
||||||
## 文件通道
|
|
||||||
|
|
||||||
core 通过同一条连接搬文件,**设备不需要任何额外端口**:
|
|
||||||
|
|
||||||
| 方向 | 流程 |
|
|
||||||
|---|---|
|
|
||||||
| 拉取(设备 → 会话目录) | `file{op:read}` → 设备分块回 `file.chunk` → `file.done{size,sha256}` |
|
|
||||||
| 推送(会话目录 → 设备) | `file{op:write,size,sha256}` → 分块 `file.chunk` → `file.done` |
|
|
||||||
|
|
||||||
- 每块 256 KiB(base64 后约 341 KiB),单文件上限 2 GiB;
|
|
||||||
- 超时按**空闲**算:首块 30s,之后每收到一块重置 30s——链路慢但不卡就不会被误杀;
|
|
||||||
- 写盘先落 `<path>.part`,`size` 与 `sha256` 都对上才 `rename`;
|
|
||||||
- 设备侧路径必须在工作根内(与 `exec` 的 cwd 校验同一套)。
|
|
||||||
|
|
||||||
## 安全边界
|
|
||||||
|
|
||||||
- 设备主动出站,服务端不需要知道设备 IP;
|
|
||||||
- token 走 `Authorization: Bearer`,与业务 token 分开;
|
|
||||||
- `cwd` 只约束**起始目录**,命令内部仍可 `cd` 到别处——给了 shell 就是这个语义,需要强隔离请用容器/namespaces;
|
|
||||||
- 同一个 token 可被多台设备共用(当前设计),吊销需换 token 并重启所有设备。
|
|
||||||
|
|
||||||
## 实测
|
|
||||||
|
|
||||||
| 用例 | 结果 |
|
|
||||||
|---|---|
|
|
||||||
| exec 基本 | cwd 自动创建,stdout/stderr 分流,退出码透传 |
|
|
||||||
| 超时 | 杀进程组,`killed_by=timeout` |
|
|
||||||
| 起始 cwd 越界 | 拒绝 |
|
|
||||||
| 断线重连 | 1s→2s→4s 退避,恢复后自动注册 |
|
|
||||||
|
|
||||||
在 Linux / macOS / Windows 三平台编译验证(amd64 + arm64);另出 `linux-mips` 软浮点版给 OpenWrt 设备。
|
|
||||||
@@ -1,237 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
// 文件通道:core 通过同一条 WS 拉取 / 推送文件。
|
|
||||||
//
|
|
||||||
// 协议(与 core 的 devices.js 一一对应):
|
|
||||||
//
|
|
||||||
// core → 节点 {t:"file", id, op:"read", path}
|
|
||||||
// 节点 → core {t:"file.chunk", id, data:<base64>} ×N → {t:"file.done", id, size, sha256}
|
|
||||||
//
|
|
||||||
// core → 节点 {t:"file", id, op:"write", path, size, sha256}
|
|
||||||
// core → 节点 {t:"file.chunk", id, data} ×N → {t:"file.done", id}
|
|
||||||
// 节点 → core {t:"file.done", id, size} 或 {t:"file.done", id, err}
|
|
||||||
//
|
|
||||||
// 写盘一律先落 <path>.part,校验通过再 rename——半截文件不能留在原地。
|
|
||||||
|
|
||||||
import (
|
|
||||||
"crypto/sha256"
|
|
||||||
"encoding/hex"
|
|
||||||
"errors"
|
|
||||||
"hash"
|
|
||||||
"io"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
"sync"
|
|
||||||
|
|
||||||
"agent-device/pkg/wsnode"
|
|
||||||
"agent-device/pkg/proto"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
fileChunkSize = 256 << 10 // 每块 256 KiB(base64 后约 341 KiB)
|
|
||||||
maxFileBytes = 2 << 30 // 单文件上限 2 GiB
|
|
||||||
)
|
|
||||||
|
|
||||||
type fileWriter struct {
|
|
||||||
path string
|
|
||||||
tmp *os.File
|
|
||||||
tmpPath string
|
|
||||||
hash hash.Hash
|
|
||||||
got int64
|
|
||||||
// 期望值(core 下发时给的,用于对账)
|
|
||||||
size int64
|
|
||||||
sha string
|
|
||||||
}
|
|
||||||
|
|
||||||
type fileMgr struct {
|
|
||||||
mu sync.Mutex
|
|
||||||
writers map[string]*fileWriter
|
|
||||||
}
|
|
||||||
|
|
||||||
func newFileMgr() *fileMgr {
|
|
||||||
return &fileMgr{writers: map[string]*fileWriter{}}
|
|
||||||
}
|
|
||||||
|
|
||||||
// safePath 把设备侧路径限制在 root 之内(与 exec 的 cwd 校验同一套语义)。
|
|
||||||
func (r *runner) safePath(raw string) (string, error) {
|
|
||||||
if raw == "" {
|
|
||||||
return "", errors.New("path 不能为空")
|
|
||||||
}
|
|
||||||
p := raw
|
|
||||||
if !filepath.IsAbs(p) {
|
|
||||||
p = filepath.Join(r.root, p)
|
|
||||||
}
|
|
||||||
p = filepath.Clean(p)
|
|
||||||
rel, err := filepath.Rel(r.root, p)
|
|
||||||
if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
|
|
||||||
return "", errors.New("path 超出工作根:" + raw)
|
|
||||||
}
|
|
||||||
return p, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *runner) fileStart(c *wsnode.Conn, m proto.Msg) {
|
|
||||||
switch m.Op {
|
|
||||||
case "read":
|
|
||||||
go r.fileRead(c, m)
|
|
||||||
case "write":
|
|
||||||
r.fileBegin(c, m)
|
|
||||||
default:
|
|
||||||
r.fileFail(c, m.ID, "未知的 file.op:"+m.Op)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *runner) fileFail(c *wsnode.Conn, id, msg string) {
|
|
||||||
_ = c.Send(proto.Msg{T: proto.TKindFileDone, ID: id, Err: msg})
|
|
||||||
}
|
|
||||||
|
|
||||||
// fileRead 把设备上的文件分块推回 core。
|
|
||||||
func (r *runner) fileRead(c *wsnode.Conn, m proto.Msg) {
|
|
||||||
p, err := r.safePath(m.Path)
|
|
||||||
if err != nil {
|
|
||||||
r.fileFail(c, m.ID, err.Error())
|
|
||||||
return
|
|
||||||
}
|
|
||||||
f, err := os.Open(p)
|
|
||||||
if err != nil {
|
|
||||||
r.fileFail(c, m.ID, err.Error())
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer f.Close()
|
|
||||||
|
|
||||||
st, err := f.Stat()
|
|
||||||
if err != nil {
|
|
||||||
r.fileFail(c, m.ID, err.Error())
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if st.IsDir() {
|
|
||||||
r.fileFail(c, m.ID, "是目录,不是文件:"+p)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if st.Size() > maxFileBytes {
|
|
||||||
r.fileFail(c, m.ID, "文件超过 2GiB 上限")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
h := sha256.New()
|
|
||||||
buf := make([]byte, fileChunkSize)
|
|
||||||
var sent int64
|
|
||||||
for {
|
|
||||||
n, rerr := f.Read(buf)
|
|
||||||
if n > 0 {
|
|
||||||
h.Write(buf[:n])
|
|
||||||
sent += int64(n)
|
|
||||||
if err := c.Send(proto.Msg{
|
|
||||||
T: proto.TKindFileChunk, ID: m.ID,
|
|
||||||
Data: append([]byte(nil), buf[:n]...),
|
|
||||||
}); err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if rerr == io.EOF {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
if rerr != nil {
|
|
||||||
r.fileFail(c, m.ID, rerr.Error())
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ = c.Send(proto.Msg{
|
|
||||||
T: proto.TKindFileDone, ID: m.ID,
|
|
||||||
Size: sent, SHA: hex.EncodeToString(h.Sum(nil)),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// fileBegin 为一次 write 建立临时文件。
|
|
||||||
func (r *runner) fileBegin(c *wsnode.Conn, m proto.Msg) {
|
|
||||||
p, err := r.safePath(m.Path)
|
|
||||||
if err != nil {
|
|
||||||
r.fileFail(c, m.ID, err.Error())
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if m.Size > maxFileBytes {
|
|
||||||
r.fileFail(c, m.ID, "文件超过 2GiB 上限")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
|
|
||||||
r.fileFail(c, m.ID, err.Error())
|
|
||||||
return
|
|
||||||
}
|
|
||||||
tmpPath := p + ".part"
|
|
||||||
f, err := os.OpenFile(tmpPath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o644)
|
|
||||||
if err != nil {
|
|
||||||
r.fileFail(c, m.ID, err.Error())
|
|
||||||
return
|
|
||||||
}
|
|
||||||
r.files.mu.Lock()
|
|
||||||
r.files.writers[m.ID] = &fileWriter{
|
|
||||||
path: p, tmp: f, tmpPath: tmpPath, hash: sha256.New(),
|
|
||||||
size: m.Size, sha: m.SHA,
|
|
||||||
}
|
|
||||||
r.files.mu.Unlock()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *runner) fileChunk(c *wsnode.Conn, m proto.Msg) {
|
|
||||||
r.files.mu.Lock()
|
|
||||||
w := r.files.writers[m.ID]
|
|
||||||
r.files.mu.Unlock()
|
|
||||||
if w == nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if w.got+int64(len(m.Data)) > maxFileBytes {
|
|
||||||
r.abortWriter(m.ID, w, "超过 2GiB 上限")
|
|
||||||
r.fileFail(c, m.ID, "超过 2GiB 上限")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if _, err := w.tmp.Write(m.Data); err != nil {
|
|
||||||
r.abortWriter(m.ID, w, err.Error())
|
|
||||||
r.fileFail(c, m.ID, err.Error())
|
|
||||||
return
|
|
||||||
}
|
|
||||||
w.hash.Write(m.Data)
|
|
||||||
w.got += int64(len(m.Data))
|
|
||||||
}
|
|
||||||
|
|
||||||
// fileEnd 收尾写入:校验大小与 sha256,通过才改名到正式路径。
|
|
||||||
func (r *runner) fileEnd(c *wsnode.Conn, m proto.Msg) {
|
|
||||||
r.files.mu.Lock()
|
|
||||||
w := r.files.writers[m.ID]
|
|
||||||
delete(r.files.writers, m.ID)
|
|
||||||
r.files.mu.Unlock()
|
|
||||||
if w == nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer func() { _ = w.tmp.Close() }()
|
|
||||||
|
|
||||||
sum := hex.EncodeToString(w.hash.Sum(nil))
|
|
||||||
if w.size > 0 && w.got != w.size {
|
|
||||||
_ = os.Remove(w.tmpPath)
|
|
||||||
r.fileFail(c, m.ID, "大小不符:收到 "+strconv.FormatInt(w.got, 10)+",应为 "+strconv.FormatInt(w.size, 10))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if w.sha != "" && !strings.EqualFold(w.sha, sum) {
|
|
||||||
_ = os.Remove(w.tmpPath)
|
|
||||||
r.fileFail(c, m.ID, "sha256 不符")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if err := w.tmp.Close(); err != nil {
|
|
||||||
_ = os.Remove(w.tmpPath)
|
|
||||||
r.fileFail(c, m.ID, err.Error())
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if err := os.Rename(w.tmpPath, w.path); err != nil {
|
|
||||||
_ = os.Remove(w.tmpPath)
|
|
||||||
r.fileFail(c, m.ID, err.Error())
|
|
||||||
return
|
|
||||||
}
|
|
||||||
_ = c.Send(proto.Msg{T: proto.TKindFileDone, ID: m.ID, Size: w.got, SHA: sum})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *runner) abortWriter(id string, w *fileWriter, why string) {
|
|
||||||
r.files.mu.Lock()
|
|
||||||
delete(r.files.writers, id)
|
|
||||||
r.files.mu.Unlock()
|
|
||||||
_ = w.tmp.Close()
|
|
||||||
_ = os.Remove(w.tmpPath)
|
|
||||||
}
|
|
||||||
@@ -1,162 +0,0 @@
|
|||||||
//go:build !windows
|
|
||||||
|
|
||||||
package main
|
|
||||||
|
|
||||||
// 主机指标:Linux 读 /proc,macOS 调 sysctl / vm_stat(health 调用不频繁,允许 fork)。
|
|
||||||
// 拿不到的指标给 -1,不编数据。
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"os"
|
|
||||||
"os/exec"
|
|
||||||
"runtime"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
"syscall"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
type healthInfo struct {
|
|
||||||
HostUptimeSec int64
|
|
||||||
Load1, Load5, Load15 float64
|
|
||||||
MemTotalMB, MemFreeMB int64
|
|
||||||
DiskTotalGB, DiskFreeGB float64
|
|
||||||
TempC float64
|
|
||||||
}
|
|
||||||
|
|
||||||
func hostHealth() healthInfo {
|
|
||||||
h := healthInfo{
|
|
||||||
HostUptimeSec: -1, Load1: -1, Load5: -1, Load15: -1,
|
|
||||||
MemTotalMB: -1, MemFreeMB: -1, DiskTotalGB: -1, DiskFreeGB: -1, TempC: -1,
|
|
||||||
}
|
|
||||||
|
|
||||||
switch runtime.GOOS {
|
|
||||||
case "linux":
|
|
||||||
if b, err := os.ReadFile("/proc/uptime"); err == nil {
|
|
||||||
if f := strings.Fields(string(b)); len(f) > 0 {
|
|
||||||
if v, err := strconv.ParseFloat(f[0], 64); err == nil {
|
|
||||||
h.HostUptimeSec = int64(v)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if b, err := os.ReadFile("/proc/loadavg"); err == nil {
|
|
||||||
if f := strings.Fields(string(b)); len(f) >= 3 {
|
|
||||||
h.Load1, _ = strconv.ParseFloat(f[0], 64)
|
|
||||||
h.Load5, _ = strconv.ParseFloat(f[1], 64)
|
|
||||||
h.Load15, _ = strconv.ParseFloat(f[2], 64)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if b, err := os.ReadFile("/proc/meminfo"); err == nil {
|
|
||||||
for _, line := range strings.Split(string(b), "\n") {
|
|
||||||
f := strings.Fields(line)
|
|
||||||
if len(f) < 2 {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
kb, _ := strconv.ParseInt(f[1], 10, 64)
|
|
||||||
switch f[0] {
|
|
||||||
case "MemTotal:":
|
|
||||||
h.MemTotalMB = kb / 1024
|
|
||||||
case "MemAvailable:":
|
|
||||||
h.MemFreeMB = kb / 1024
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if b, err := os.ReadFile("/sys/class/thermal/thermal_zone0/temp"); err == nil {
|
|
||||||
if v, err := strconv.ParseFloat(strings.TrimSpace(string(b)), 64); err == nil {
|
|
||||||
h.TempC = v / 1000
|
|
||||||
}
|
|
||||||
}
|
|
||||||
case "darwin":
|
|
||||||
// macOS 没有 /proc,走 sysctl / vm_stat;每次 health 只 fork 三四个进程,频率极低
|
|
||||||
if v, err := sysctlValue("hw.memsize"); err == nil {
|
|
||||||
if n, err := strconv.ParseInt(v, 10, 64); err == nil {
|
|
||||||
h.MemTotalMB = n >> 20
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// 开机时长:kern.boottime 形如 { sec = 1794298276, usec = 155984 } Tue Nov 10 …
|
|
||||||
if v, err := sysctlValue("kern.boottime"); err == nil {
|
|
||||||
if i := strings.Index(v, "sec = "); i >= 0 {
|
|
||||||
rest := v[i+6:]
|
|
||||||
if j := strings.IndexAny(rest, ",}"); j > 0 {
|
|
||||||
if sec, err := strconv.ParseInt(strings.TrimSpace(rest[:j]), 10, 64); err == nil {
|
|
||||||
h.HostUptimeSec = time.Now().Unix() - sec
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// 负载:vm.loadavg 形如 { 1.11 1.40 1.59 }
|
|
||||||
if v, err := sysctlValue("vm.loadavg"); err == nil {
|
|
||||||
f := strings.FieldsFunc(v, func(r rune) bool { return r == '{' || r == '}' || r == ' ' })
|
|
||||||
if len(f) >= 3 {
|
|
||||||
h.Load1, _ = strconv.ParseFloat(f[0], 64)
|
|
||||||
h.Load5, _ = strconv.ParseFloat(f[1], 64)
|
|
||||||
h.Load15, _ = strconv.ParseFloat(f[2], 64)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// 可用内存 ≈ free + inactive + speculative:macOS 上只看 free 会小得吓人(大半是缓存)
|
|
||||||
if mb := darwinAvailableMB(); mb >= 0 {
|
|
||||||
h.MemFreeMB = mb
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var st syscall.Statfs_t
|
|
||||||
if err := syscall.Statfs("/", &st); err == nil {
|
|
||||||
h.DiskTotalGB = float64(st.Blocks) * float64(st.Bsize) / (1 << 30)
|
|
||||||
h.DiskFreeGB = float64(st.Bavail) * float64(st.Bsize) / (1 << 30)
|
|
||||||
}
|
|
||||||
return h
|
|
||||||
}
|
|
||||||
|
|
||||||
// sysctlValue 读一个 sysctl 键,1s 超时兜底。
|
|
||||||
func sysctlValue(key string) (string, error) {
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
|
||||||
defer cancel()
|
|
||||||
out, err := exec.CommandContext(ctx, "sysctl", "-n", key).Output()
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
return strings.TrimSpace(string(out)), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// darwinAvailableMB 解析 vm_stat,返回 free+inactive+speculative 的 MB 数;解析失败给 -1。
|
|
||||||
func darwinAvailableMB() int64 {
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 1200*time.Millisecond)
|
|
||||||
defer cancel()
|
|
||||||
out, err := exec.CommandContext(ctx, "vm_stat").Output()
|
|
||||||
if err != nil {
|
|
||||||
return -1
|
|
||||||
}
|
|
||||||
pageSize := int64(4096)
|
|
||||||
free, inactive, speculative := int64(-1), int64(0), int64(0)
|
|
||||||
for _, line := range strings.Split(string(out), "\n") {
|
|
||||||
if i := strings.Index(line, "page size of "); i >= 0 {
|
|
||||||
rest := line[i+len("page size of "):]
|
|
||||||
if j := strings.Index(rest, " bytes"); j > 0 {
|
|
||||||
if v, err := strconv.ParseInt(rest[:j], 10, 64); err == nil {
|
|
||||||
pageSize = v
|
|
||||||
}
|
|
||||||
}
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
num := func(prefix string) (int64, bool) {
|
|
||||||
if !strings.HasPrefix(line, prefix) {
|
|
||||||
return 0, false
|
|
||||||
}
|
|
||||||
v, err := strconv.ParseInt(strings.TrimSuffix(strings.TrimSpace(line[len(prefix):]), "."), 10, 64)
|
|
||||||
return v, err == nil
|
|
||||||
}
|
|
||||||
if v, ok := num("Pages free:"); ok {
|
|
||||||
free = v
|
|
||||||
}
|
|
||||||
if v, ok := num("Pages inactive:"); ok {
|
|
||||||
inactive = v
|
|
||||||
}
|
|
||||||
if v, ok := num("Pages speculative:"); ok {
|
|
||||||
speculative = v
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if free < 0 {
|
|
||||||
return -1
|
|
||||||
}
|
|
||||||
return (free + inactive + speculative) * pageSize / (1 << 20)
|
|
||||||
}
|
|
||||||
@@ -1,67 +0,0 @@
|
|||||||
//go:build windows
|
|
||||||
|
|
||||||
package main
|
|
||||||
|
|
||||||
// Windows 指标:GetTickCount64(开机时长)+ GlobalMemoryStatusEx + GetDiskFreeSpaceExW。
|
|
||||||
// 负载/温度在 Windows 上没有等价指标,返回 -1。
|
|
||||||
|
|
||||||
import (
|
|
||||||
"syscall"
|
|
||||||
"unsafe"
|
|
||||||
)
|
|
||||||
|
|
||||||
type healthInfo struct {
|
|
||||||
HostUptimeSec int64
|
|
||||||
Load1, Load5, Load15 float64
|
|
||||||
MemTotalMB, MemFreeMB int64
|
|
||||||
DiskTotalGB, DiskFreeGB float64
|
|
||||||
TempC float64
|
|
||||||
}
|
|
||||||
|
|
||||||
var (
|
|
||||||
kernel32 = syscall.NewLazyDLL("kernel32.dll")
|
|
||||||
procTick = kernel32.NewProc("GetTickCount64")
|
|
||||||
procMem = kernel32.NewProc("GlobalMemoryStatusEx")
|
|
||||||
procDiskF = kernel32.NewProc("GetDiskFreeSpaceExW")
|
|
||||||
)
|
|
||||||
|
|
||||||
type memStatusEx struct {
|
|
||||||
Length uint32
|
|
||||||
MemoryLoad uint32
|
|
||||||
TotalPhys uint64
|
|
||||||
AvailPhys uint64
|
|
||||||
TotalPageFile uint64
|
|
||||||
AvailPageFile uint64
|
|
||||||
TotalVirtual uint64
|
|
||||||
AvailVirtual uint64
|
|
||||||
AvailExtendedVirtual uint64
|
|
||||||
}
|
|
||||||
|
|
||||||
func hostHealth() healthInfo {
|
|
||||||
h := healthInfo{
|
|
||||||
HostUptimeSec: -1, Load1: -1, Load5: -1, Load15: -1,
|
|
||||||
MemTotalMB: -1, MemFreeMB: -1, DiskTotalGB: -1, DiskFreeGB: -1, TempC: -1,
|
|
||||||
}
|
|
||||||
if r, _, _ := procTick.Call(); r != 0 {
|
|
||||||
h.HostUptimeSec = int64(r / 1000)
|
|
||||||
}
|
|
||||||
var m memStatusEx
|
|
||||||
m.Length = uint32(unsafe.Sizeof(m))
|
|
||||||
if r, _, _ := procMem.Call(uintptr(unsafe.Pointer(&m))); r != 0 {
|
|
||||||
h.MemTotalMB = int64(m.TotalPhys >> 20)
|
|
||||||
h.MemFreeMB = int64(m.AvailPhys >> 20)
|
|
||||||
}
|
|
||||||
if p, err := syscall.UTF16PtrFromString("C:\\"); err == nil {
|
|
||||||
var free, total, totalFree uint64
|
|
||||||
if r, _, _ := procDiskF.Call(
|
|
||||||
uintptr(unsafe.Pointer(p)),
|
|
||||||
uintptr(unsafe.Pointer(&free)),
|
|
||||||
uintptr(unsafe.Pointer(&total)),
|
|
||||||
uintptr(unsafe.Pointer(&totalFree)),
|
|
||||||
); r != 0 {
|
|
||||||
h.DiskTotalGB = float64(total) / (1 << 30)
|
|
||||||
h.DiskFreeGB = float64(free) / (1 << 30)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return h
|
|
||||||
}
|
|
||||||
@@ -1,522 +0,0 @@
|
|||||||
// agent-device:跑在盒子 / Windows / 任意 Linux 上,主动出站连 core 的 wss,接收并执行命令。
|
|
||||||
//
|
|
||||||
// agent-device -server wss://your-host.example/dev/ws -token <TOKEN> -root /var/agent/work
|
|
||||||
// agent-device # 自动读同目录下的 config.json(token 不进 ps)
|
|
||||||
//
|
|
||||||
// 设计约束(对齐 files/print/agent):
|
|
||||||
// - 只出站,服务器不需要任何入站端口
|
|
||||||
// - 断线指数退避重连,半开连接靠读超时兜底
|
|
||||||
// - 单机不依赖 Node / 不装运行时,一个二进制跑起来
|
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
"flag"
|
|
||||||
"io"
|
|
||||||
"log"
|
|
||||||
"os"
|
|
||||||
"os/exec"
|
|
||||||
"path/filepath"
|
|
||||||
"runtime"
|
|
||||||
"strings"
|
|
||||||
"sync"
|
|
||||||
"sync/atomic"
|
|
||||||
"time"
|
|
||||||
"unicode/utf8"
|
|
||||||
|
|
||||||
"agent-device/pkg/proto"
|
|
||||||
"agent-device/pkg/wsnode"
|
|
||||||
"golang.org/x/text/encoding/simplifiedchinese"
|
|
||||||
)
|
|
||||||
|
|
||||||
const version = "0.1.1"
|
|
||||||
|
|
||||||
var (
|
|
||||||
maxOutBytes = int64(4 << 20) // 单条命令回传上限,超出截断并标记
|
|
||||||
maxParallel = 4 // 同机并发执行数
|
|
||||||
)
|
|
||||||
|
|
||||||
type proc struct {
|
|
||||||
cmd *exec.Cmd
|
|
||||||
mu sync.Mutex
|
|
||||||
kln string // 终止原因:cancelled / timeout
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *proc) kill(reason string) {
|
|
||||||
p.mu.Lock()
|
|
||||||
if p.kln == "" {
|
|
||||||
p.kln = reason
|
|
||||||
}
|
|
||||||
p.mu.Unlock()
|
|
||||||
killProc(p.cmd)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *proc) killed() string {
|
|
||||||
p.mu.Lock()
|
|
||||||
defer p.mu.Unlock()
|
|
||||||
return p.kln
|
|
||||||
}
|
|
||||||
|
|
||||||
// fileConfig 是 -config 读的 JSON,字段全部可选:没写的落到命令行/默认值。
|
|
||||||
// 之所以需要它:token 写在命令行会被 ps 看见。
|
|
||||||
type fileConfig struct {
|
|
||||||
Server string `json:"server"`
|
|
||||||
Token string `json:"token"`
|
|
||||||
Root string `json:"root"`
|
|
||||||
Name string `json:"name"`
|
|
||||||
Shell string `json:"shell"`
|
|
||||||
Insecure *bool `json:"insecure"`
|
|
||||||
}
|
|
||||||
|
|
||||||
var startedAt = time.Now()
|
|
||||||
|
|
||||||
type runner struct {
|
|
||||||
conn *wsnode.Conn
|
|
||||||
root string
|
|
||||||
shell string
|
|
||||||
sem chan struct{}
|
|
||||||
|
|
||||||
mu sync.Mutex
|
|
||||||
procs map[string]*proc
|
|
||||||
|
|
||||||
files *fileMgr // 文件通道:core 拉取/推送文件时的在途写入
|
|
||||||
}
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
server := flag.String("server", "", "core 的接入地址,如 wss://your-host.example/dev/ws")
|
|
||||||
token := flag.String("token", "", "Bearer token(或环境变量 NODE_TOKEN,或写在 -config 里)")
|
|
||||||
root := flag.String("root", "", "工作根目录(默认 ~/agent-work),命令的 cwd 必须落在它之内")
|
|
||||||
shellName := flag.String("shell", "", "sh | cmd | powershell(默认按平台)")
|
|
||||||
name := flag.String("name", "", "设备名(默认 hostname)")
|
|
||||||
configPath := flag.String("config", "", "JSON 配置文件;不给时自动找可执行文件同目录的 config.json")
|
|
||||||
insecure := flag.Bool("insecure", false, "跳过证书校验")
|
|
||||||
fixClock := flag.Bool("fix-clock", false, "证书失败时用服务器时间校准本机(Linux 需 root)")
|
|
||||||
flag.Parse()
|
|
||||||
|
|
||||||
// 优先级:命令行显式参数 > 环境变量(仅 token)> 配置文件 > 默认值。
|
|
||||||
// 配置文件的意义是把 token 从命令行拿掉——ps aux 能看见所有参数。
|
|
||||||
set := map[string]bool{}
|
|
||||||
flag.Visit(func(f *flag.Flag) { set[f.Name] = true })
|
|
||||||
// 配置文件默认位置:可执行文件同目录的 config.json。放二进制旁边就不用带参数,
|
|
||||||
// token 也不会出现在 ps 里。命令行显式给的 -config 优先。
|
|
||||||
effectiveCfg := *configPath
|
|
||||||
if effectiveCfg == "" {
|
|
||||||
if dir := exeDir(); dir != "" {
|
|
||||||
p := filepath.Join(dir, "config.json")
|
|
||||||
if _, err := os.Stat(p); err == nil {
|
|
||||||
effectiveCfg = p
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if effectiveCfg != "" {
|
|
||||||
var fc fileConfig
|
|
||||||
b, err := os.ReadFile(effectiveCfg)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatalf("读配置失败:%v", err)
|
|
||||||
}
|
|
||||||
if err := json.Unmarshal(b, &fc); err != nil {
|
|
||||||
log.Fatalf("配置 %s 不是合法 JSON:%v", effectiveCfg, err)
|
|
||||||
}
|
|
||||||
log.Printf("已加载配置 %s", effectiveCfg)
|
|
||||||
if !set["server"] && fc.Server != "" {
|
|
||||||
*server = fc.Server
|
|
||||||
}
|
|
||||||
if !set["token"] && fc.Token != "" {
|
|
||||||
*token = fc.Token
|
|
||||||
}
|
|
||||||
if !set["root"] && fc.Root != "" {
|
|
||||||
*root = fc.Root
|
|
||||||
}
|
|
||||||
if !set["name"] && fc.Name != "" {
|
|
||||||
*name = fc.Name
|
|
||||||
}
|
|
||||||
if !set["shell"] && fc.Shell != "" {
|
|
||||||
*shellName = fc.Shell
|
|
||||||
}
|
|
||||||
if !set["insecure"] && fc.Insecure != nil {
|
|
||||||
*insecure = *fc.Insecure
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if *token == "" {
|
|
||||||
*token = os.Getenv("NODE_TOKEN")
|
|
||||||
}
|
|
||||||
|
|
||||||
if *server == "" {
|
|
||||||
log.Fatal("缺少 -server(或配置文件里的 server)")
|
|
||||||
}
|
|
||||||
if *token == "" {
|
|
||||||
log.Fatal("缺少 token:用 -token / NODE_TOKEN / 配置文件")
|
|
||||||
}
|
|
||||||
|
|
||||||
r := &runner{
|
|
||||||
root: *root,
|
|
||||||
shell: *shellName,
|
|
||||||
sem: make(chan struct{}, maxParallel),
|
|
||||||
procs: map[string]*proc{},
|
|
||||||
files: newFileMgr(),
|
|
||||||
}
|
|
||||||
if r.root == "" {
|
|
||||||
home, _ := os.UserHomeDir()
|
|
||||||
r.root = filepath.Join(home, "agent-work")
|
|
||||||
}
|
|
||||||
r.root = filepath.Clean(r.root)
|
|
||||||
// 相对路径按可执行文件所在目录解析:双击、服务、命令行启动都得到同一个工作区,
|
|
||||||
// 不受进程当前目录影响;同时不允许用 ".." 跑到 exe 目录之外。
|
|
||||||
if !filepath.IsAbs(r.root) {
|
|
||||||
dir := exeDir()
|
|
||||||
if dir == "" {
|
|
||||||
log.Fatalf("工作根 %q 是相对路径,但取不到可执行文件位置", r.root)
|
|
||||||
}
|
|
||||||
abs := filepath.Join(dir, r.root)
|
|
||||||
rel, err := filepath.Rel(dir, abs)
|
|
||||||
if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
|
|
||||||
log.Fatalf("工作根 %q 超出可执行文件目录:%s", r.root, abs)
|
|
||||||
}
|
|
||||||
r.root = abs
|
|
||||||
}
|
|
||||||
if err := os.MkdirAll(r.root, 0o755); err != nil {
|
|
||||||
log.Fatalf("工作根不可用:%v", err)
|
|
||||||
}
|
|
||||||
// 进程 cwd 失效时(快捷方式的「起始位置」指向已删目录、启动目录被改名等),
|
|
||||||
// Windows 上 os/exec 给 nil Stdin 打开空设备 "NUL" 是个相对路径调用,会直接报
|
|
||||||
// 「找不到文件」,任何命令都起不来(含下面的 shellInfo 探测)。工作根刚 MkdirAll 过,
|
|
||||||
// 钉在这里;失败也不致命,后面 run() 还有一层不依赖 NUL 的兵底。
|
|
||||||
if err := os.Chdir(r.root); err != nil {
|
|
||||||
log.Printf("切换工作目录失败(不影响命令执行):%v", err)
|
|
||||||
}
|
|
||||||
if r.shell == "" {
|
|
||||||
r.shell = defaultShell()
|
|
||||||
}
|
|
||||||
host, _ := os.Hostname()
|
|
||||||
if *name != "" {
|
|
||||||
host = *name
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Printf("agent-device %s 启动:root=%s shell=%s → %s", version, r.root, shellKind(r.shell), *server)
|
|
||||||
shPath, shVer := shellInfo(r.shell)
|
|
||||||
log.Printf("shell:%s(%s %s)", r.shell, shPath, shVer)
|
|
||||||
cfg := wsnode.Config{URL: *server, Token: *token, Insecure: *insecure, FixClock: *fixClock}
|
|
||||||
err := wsnode.Run(context.Background(), cfg,
|
|
||||||
func(c *wsnode.Conn) error {
|
|
||||||
r.conn = c
|
|
||||||
if err := c.Send(proto.Msg{
|
|
||||||
T: proto.TKindHello, Ver: version, Name: host,
|
|
||||||
OS: runtime.GOOS, Arch: runtime.GOARCH,
|
|
||||||
Shell: shellKind(r.shell), ShellPath: shPath, ShellVer: shVer, Root: r.root,
|
|
||||||
}); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
log.Printf("已连上 hub(%s/%s shell=%s %s)", runtime.GOOS, runtime.GOARCH, shPath, shVer)
|
|
||||||
return nil
|
|
||||||
},
|
|
||||||
func(c *wsnode.Conn, t string, raw []byte) {
|
|
||||||
var m proto.Msg
|
|
||||||
if json.Unmarshal(raw, &m) != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
switch t {
|
|
||||||
case proto.TKindExec:
|
|
||||||
go r.run(m)
|
|
||||||
case proto.TKindKill:
|
|
||||||
if p := r.lookup(m.ID); p != nil {
|
|
||||||
p.kill("cancelled")
|
|
||||||
}
|
|
||||||
case proto.TKindPing:
|
|
||||||
_ = c.Send(proto.Msg{T: proto.TKindPong})
|
|
||||||
case proto.TKindFile:
|
|
||||||
// write 的建栅必须同步完成:core 紧接着就发 chunk,异步会先到后建、丢块
|
|
||||||
r.fileStart(c, m)
|
|
||||||
case proto.TKindFileChunk:
|
|
||||||
r.fileChunk(c, m)
|
|
||||||
case proto.TKindFileDone:
|
|
||||||
r.fileEnd(c, m)
|
|
||||||
case proto.TKindHealth:
|
|
||||||
h := hostHealth()
|
|
||||||
m := proto.Msg{
|
|
||||||
T: proto.TKindHealth, ID: m.ID,
|
|
||||||
UptimeSec: int64(time.Since(startedAt).Seconds()), HostUptimeSec: h.HostUptimeSec,
|
|
||||||
Load1: h.Load1, Load5: h.Load5, Load15: h.Load15,
|
|
||||||
MemTotalMB: h.MemTotalMB, MemFreeMB: h.MemFreeMB,
|
|
||||||
DiskTotalGB: h.DiskTotalGB, DiskFreeGB: h.DiskFreeGB, TempC: h.TempC,
|
|
||||||
OS: runtime.GOOS, Arch: runtime.GOARCH, Name: host,
|
|
||||||
}
|
|
||||||
_ = c.Send(m)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
log.Printf("退出:%v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *runner) lookup(id string) *proc {
|
|
||||||
r.mu.Lock()
|
|
||||||
defer r.mu.Unlock()
|
|
||||||
return r.procs[id]
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *runner) send(m proto.Msg) { _ = r.conn.Send(m) }
|
|
||||||
|
|
||||||
func (r *runner) exit(id string, code int, killed, errMsg string, truncated bool, ms int64) {
|
|
||||||
m := proto.Msg{T: proto.TKindExit, ID: id, Code: &code, Killed: killed, Err: errMsg, MS: ms, Truncated: truncated}
|
|
||||||
r.send(m)
|
|
||||||
}
|
|
||||||
|
|
||||||
// run 执行一条命令:并发闸门 → cwd 校验 → 起进程组 → 流式回传 → 退出码。
|
|
||||||
func (r *runner) run(m proto.Msg) {
|
|
||||||
select {
|
|
||||||
case r.sem <- struct{}{}:
|
|
||||||
case <-time.After(30 * time.Second):
|
|
||||||
r.exit(m.ID, -1, "", "节点忙:排队超过 30 秒", false, 0)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer func() { <-r.sem }()
|
|
||||||
|
|
||||||
dir, err := r.resolveCwd(m.Cwd)
|
|
||||||
if err != nil {
|
|
||||||
r.exit(m.ID, -1, "", err.Error(), false, 0)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
tmo := time.Duration(m.TimeoutMS) * time.Millisecond
|
|
||||||
if tmo <= 0 {
|
|
||||||
tmo = 5 * time.Minute
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), tmo)
|
|
||||||
defer cancel()
|
|
||||||
|
|
||||||
sh, shArgs := shellCmd(r.shell)
|
|
||||||
cmd := newCmd(ctx, sh, append(shArgs, m.Cmd)...)
|
|
||||||
cmd.Dir = dir
|
|
||||||
if len(m.Env) > 0 {
|
|
||||||
cmd.Env = append(os.Environ(), flatten(m.Env)...)
|
|
||||||
}
|
|
||||||
cmd.Cancel = func() error { killProc(cmd); return nil } // 超时/取消时整组杀,不只杀 sh
|
|
||||||
setupProc(cmd)
|
|
||||||
|
|
||||||
outPipe, err1 := cmd.StdoutPipe()
|
|
||||||
errPipe, err2 := cmd.StderrPipe()
|
|
||||||
if err1 != nil || err2 != nil {
|
|
||||||
r.exit(m.ID, 127, "", "取管道失败", false, 0)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
p := &proc{cmd: cmd}
|
|
||||||
r.mu.Lock()
|
|
||||||
r.procs[m.ID] = p
|
|
||||||
r.mu.Unlock()
|
|
||||||
defer func() {
|
|
||||||
r.mu.Lock()
|
|
||||||
delete(r.procs, m.ID)
|
|
||||||
r.mu.Unlock()
|
|
||||||
}()
|
|
||||||
|
|
||||||
started := time.Now()
|
|
||||||
if err := cmd.Start(); err != nil {
|
|
||||||
r.exit(m.ID, 127, "", "启动失败:"+err.Error(), false, 0)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var sent atomic.Int64
|
|
||||||
var truncated atomic.Bool
|
|
||||||
var wg sync.WaitGroup
|
|
||||||
pump := func(rd io.Reader, stream string) {
|
|
||||||
defer wg.Done()
|
|
||||||
buf := make([]byte, 32<<10)
|
|
||||||
for {
|
|
||||||
n, rerr := rd.Read(buf)
|
|
||||||
if n > 0 {
|
|
||||||
if sent.Load() >= maxOutBytes {
|
|
||||||
truncated.Store(true)
|
|
||||||
} else {
|
|
||||||
chunk := make([]byte, n)
|
|
||||||
copy(chunk, buf[:n])
|
|
||||||
sent.Add(int64(n))
|
|
||||||
r.send(proto.Msg{T: proto.TKindChunk, ID: m.ID, Out: stream, Stream: chunk})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if rerr != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
wg.Add(2)
|
|
||||||
go pump(outPipe, "out")
|
|
||||||
go pump(errPipe, "err")
|
|
||||||
wg.Wait()
|
|
||||||
werr := cmd.Wait()
|
|
||||||
|
|
||||||
code := 0
|
|
||||||
if werr != nil {
|
|
||||||
var ee *exec.ExitError
|
|
||||||
if errors.As(werr, &ee) {
|
|
||||||
code = ee.ExitCode()
|
|
||||||
} else {
|
|
||||||
code = 127
|
|
||||||
}
|
|
||||||
}
|
|
||||||
killed := p.killed()
|
|
||||||
if killed == "" && ctx.Err() == context.DeadlineExceeded {
|
|
||||||
killed = "timeout"
|
|
||||||
}
|
|
||||||
if killed != "" && code == 0 {
|
|
||||||
code = -1
|
|
||||||
}
|
|
||||||
r.exit(m.ID, code, killed, "", truncated.Load(), time.Since(started).Milliseconds())
|
|
||||||
}
|
|
||||||
|
|
||||||
// resolveCwd:hub 已把服务器路径重写成节点路径,这里只保证落在 root 之内并自动建目录。
|
|
||||||
func (r *runner) resolveCwd(raw string) (string, error) {
|
|
||||||
if raw == "" {
|
|
||||||
return r.root, nil
|
|
||||||
}
|
|
||||||
if !filepath.IsAbs(raw) {
|
|
||||||
return "", errors.New("cwd 必须是绝对路径:" + raw)
|
|
||||||
}
|
|
||||||
cwd := filepath.Clean(raw)
|
|
||||||
rel, err := filepath.Rel(r.root, cwd)
|
|
||||||
if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
|
|
||||||
return "", errors.New("cwd 超出工作根:" + cwd)
|
|
||||||
}
|
|
||||||
if err := os.MkdirAll(cwd, 0o755); err != nil {
|
|
||||||
return "", errors.New("建目录失败:" + err.Error())
|
|
||||||
}
|
|
||||||
return cwd, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func flatten(env map[string]string) []string {
|
|
||||||
out := make([]string, 0, len(env))
|
|
||||||
for k, v := range env {
|
|
||||||
out = append(out, k+"="+v)
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
// exeDir 返回可执行文件所在目录(解开软链接)。相对的工作根、默认配置都基于它。
|
|
||||||
func exeDir() string {
|
|
||||||
exe, err := os.Executable()
|
|
||||||
if err != nil {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
if real, err := filepath.EvalSymlinks(exe); err == nil {
|
|
||||||
exe = real
|
|
||||||
}
|
|
||||||
return filepath.Dir(exe)
|
|
||||||
}
|
|
||||||
|
|
||||||
// defaultShell 选默认解释器。POSIX 上固定 /bin/sh(不读 $SHELL:用户把 shell 设成 fish
|
|
||||||
// 之后模型写的 POSIX 语法全废);Windows 默认 cmd,想用 git-bash / busybox 就在
|
|
||||||
// config.json 里写 "shell": "C:\\Program Files\\Git\\bin\\bash.exe"(或 PATH 里的名字)。
|
|
||||||
func defaultShell() string {
|
|
||||||
if runtime.GOOS == "windows" {
|
|
||||||
return "cmd"
|
|
||||||
}
|
|
||||||
return "sh"
|
|
||||||
}
|
|
||||||
|
|
||||||
// shellKind 把路径/命令名归成一个短标签给 core 看(hello 的 shell 字段)。
|
|
||||||
func shellKind(p string) string {
|
|
||||||
b := strings.ToLower(filepath.Base(p))
|
|
||||||
switch {
|
|
||||||
case strings.Contains(b, "busybox"):
|
|
||||||
return "busybox"
|
|
||||||
case strings.Contains(b, "bash"):
|
|
||||||
return "bash"
|
|
||||||
case b == "sh" || b == "sh.exe" || b == "/bin/sh":
|
|
||||||
return "sh"
|
|
||||||
case strings.Contains(b, "powershell"), b == "pwsh", b == "pwsh.exe":
|
|
||||||
return "powershell"
|
|
||||||
case b == "cmd" || b == "cmd.exe":
|
|
||||||
return "cmd"
|
|
||||||
}
|
|
||||||
return p
|
|
||||||
}
|
|
||||||
|
|
||||||
// newCmd 统一构造要执行的命令:Stdin 显式给一个空 reader。
|
|
||||||
// 不给(nil)时 os/exec 会自己 os.Open(os.DevNull),Windows 上那是相对路径的设备名
|
|
||||||
// "NUL"——有的机器上 CreateFile 直接报 ERROR_FILE_NOT_FOUND,命令还没到 shell 就死了
|
|
||||||
//(实测 pc-gd:所有 exec 都 exit 127 "open NUL: The system cannot find the file specified")。
|
|
||||||
// 空 reader 与 NUL 语义一致(子进程读到立即 EOF),且不依赖进程 cwd。
|
|
||||||
func newCmd(ctx context.Context, name string, args ...string) *exec.Cmd {
|
|
||||||
c := exec.CommandContext(ctx, name, args...)
|
|
||||||
c.Stdin = strings.NewReader("")
|
|
||||||
return c
|
|
||||||
}
|
|
||||||
|
|
||||||
func shellCmd(name string) (string, []string) {
|
|
||||||
switch name {
|
|
||||||
case "cmd":
|
|
||||||
return "cmd", []string{"/c"}
|
|
||||||
case "powershell", "pwsh":
|
|
||||||
return name, []string{"-NoProfile", "-NonInteractive", "-Command"}
|
|
||||||
}
|
|
||||||
// busybox 的子命令形式:busybox sh -c "…"
|
|
||||||
if strings.Contains(strings.ToLower(filepath.Base(name)), "busybox") {
|
|
||||||
return name, []string{"sh", "-c"}
|
|
||||||
}
|
|
||||||
// 带路径的(git-bash 绝对路径、/bin/sh)直接当 POSIX shell 用
|
|
||||||
if strings.ContainsAny(name, `\/`) {
|
|
||||||
return name, []string{"-c"}
|
|
||||||
}
|
|
||||||
if runtime.GOOS == "windows" {
|
|
||||||
return "cmd", []string{"/c"}
|
|
||||||
}
|
|
||||||
if _, err := os.Stat("/bin/sh"); err == nil {
|
|
||||||
return "/bin/sh", []string{"-c"}
|
|
||||||
}
|
|
||||||
return "sh", []string{"-c"}
|
|
||||||
}
|
|
||||||
|
|
||||||
// toUTF8 把 Windows 中文控制台吐出的 GBK 字节转成 UTF-8。
|
|
||||||
// 先过 utf8.Valid:纯 ASCII / 真 UTF-8(英文版 Windows、开了 UTF-8 的系统)一律原样返回,
|
|
||||||
// 不会被误转;只有不是合法 UTF-8 时才按 GBK 解,解不出来就保留原样。
|
|
||||||
func toUTF8(b []byte) []byte {
|
|
||||||
if utf8.Valid(b) {
|
|
||||||
return b
|
|
||||||
}
|
|
||||||
if d, err := simplifiedchinese.GBK.NewDecoder().Bytes(b); err == nil {
|
|
||||||
return d
|
|
||||||
}
|
|
||||||
return b
|
|
||||||
}
|
|
||||||
|
|
||||||
// shellInfo 探测实际解释器与版本。这是模型写命令的唯一入口,所以路径要解开符号链接
|
|
||||||
// (/bin/sh 可能是 dash / bash / busybox),版本拿不到就留空(dash、busybox 不支持 --version)。
|
|
||||||
func shellInfo(name string) (string, string) {
|
|
||||||
bin, _ := shellCmd(name)
|
|
||||||
p, err := exec.LookPath(bin)
|
|
||||||
if err != nil {
|
|
||||||
return "", ""
|
|
||||||
}
|
|
||||||
if real, err := filepath.EvalSymlinks(p); err == nil {
|
|
||||||
p = real
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 800*time.Millisecond)
|
|
||||||
defer cancel()
|
|
||||||
|
|
||||||
var c *exec.Cmd
|
|
||||||
switch name {
|
|
||||||
case "cmd":
|
|
||||||
c = newCmd(ctx, "cmd", "/c", "ver")
|
|
||||||
case "powershell", "pwsh":
|
|
||||||
c = newCmd(ctx, bin, "-NoProfile", "-NonInteractive", "-Command",
|
|
||||||
"$PSVersionTable.PSVersion.ToString()")
|
|
||||||
default:
|
|
||||||
c = newCmd(ctx, p, "--version")
|
|
||||||
}
|
|
||||||
out, _ := c.Output()
|
|
||||||
out = toUTF8(out) // 中文 Windows 的 ver 是 GBK;本来就是 UTF-8 的原样返回
|
|
||||||
|
|
||||||
ver := ""
|
|
||||||
if s := strings.TrimSpace(string(out)); s != "" {
|
|
||||||
if i := strings.IndexByte(s, '\n'); i > 0 {
|
|
||||||
s = s[:i]
|
|
||||||
}
|
|
||||||
s = strings.TrimSpace(s)
|
|
||||||
if len(s) > 60 {
|
|
||||||
s = s[:60] + "…"
|
|
||||||
}
|
|
||||||
ver = s
|
|
||||||
}
|
|
||||||
return p, ver
|
|
||||||
}
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
//go:build !windows
|
|
||||||
|
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"os/exec"
|
|
||||||
"syscall"
|
|
||||||
)
|
|
||||||
|
|
||||||
// setupProc 让命令自成一个进程组,后面才能整组杀(sh 拉起的子进程一起收)。
|
|
||||||
func setupProc(cmd *exec.Cmd) {
|
|
||||||
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
|
|
||||||
}
|
|
||||||
|
|
||||||
// killProc 负号 = 整个进程组。忽略错误:进程可能已自行退出。
|
|
||||||
func killProc(cmd *exec.Cmd) {
|
|
||||||
if cmd == nil || cmd.Process == nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
_ = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
|
|
||||||
}
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
//go:build windows
|
|
||||||
|
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"os/exec"
|
|
||||||
"strconv"
|
|
||||||
"syscall"
|
|
||||||
)
|
|
||||||
|
|
||||||
const createNewProcessGroup = 0x00000200
|
|
||||||
|
|
||||||
// setupProc 让命令自成一组,taskkill /T 才能连子进程一起收。
|
|
||||||
func setupProc(cmd *exec.Cmd) {
|
|
||||||
cmd.SysProcAttr = &syscall.SysProcAttr{CreationFlags: createNewProcessGroup}
|
|
||||||
}
|
|
||||||
|
|
||||||
func killProc(cmd *exec.Cmd) {
|
|
||||||
if cmd == nil || cmd.Process == nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
_ = newCmd(context.Background(), "taskkill", "/T", "/F", "/PID", strconv.Itoa(cmd.Process.Pid)).Run()
|
|
||||||
_ = cmd.Process.Kill()
|
|
||||||
}
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
module agent-device
|
|
||||||
|
|
||||||
go 1.22
|
|
||||||
|
|
||||||
require github.com/gorilla/websocket v1.5.3
|
|
||||||
|
|
||||||
require golang.org/x/text v0.21.0
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
|
||||||
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
|
||||||
golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
|
|
||||||
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
|
|
||||||
@@ -1,68 +0,0 @@
|
|||||||
// Package proto 定义 hub 与节点之间的消息。一条连接上全是 JSON 文本帧,
|
|
||||||
// 用 t 字段区分类型;二进制数据(命令输出)走 chunk 字段,encoding/json 自动 base64。
|
|
||||||
package proto
|
|
||||||
|
|
||||||
// 消息类型
|
|
||||||
const (
|
|
||||||
TKindHello = "hello" // 节点 → hub:上线自报家门
|
|
||||||
TKindExec = "exec" // hub → 节点:执行一条命令
|
|
||||||
TKindKill = "kill" // hub → 节点:终止某条命令
|
|
||||||
TKindChunk = "chunk" // 节点 → hub:输出片段
|
|
||||||
TKindExit = "exit" // 节点 → hub:命令结束
|
|
||||||
TKindPing = "ping" // hub → 节点:保活
|
|
||||||
TKindPong = "pong" // 节点 → hub:保活回应
|
|
||||||
TKindHealth = "health" // 双向:hub 要指标 / 节点回指标
|
|
||||||
TKindFile = "file" // 双向:core 发起一次 read/write
|
|
||||||
TKindFileChunk = "file.chunk" // 双向:文件数据块(base64)
|
|
||||||
TKindFileDone = "file.done" // 双向:结束,带 size / sha256 / err
|
|
||||||
)
|
|
||||||
|
|
||||||
// Msg 是双向通用信封:不同 t 只用其中一部分字段,其余 omitempty。
|
|
||||||
type Msg struct {
|
|
||||||
T string `json:"t"`
|
|
||||||
|
|
||||||
// hello
|
|
||||||
Ver string `json:"ver,omitempty"`
|
|
||||||
Name string `json:"name,omitempty"`
|
|
||||||
OS string `json:"os,omitempty"`
|
|
||||||
Arch string `json:"arch,omitempty"`
|
|
||||||
Shell string `json:"shell,omitempty"` // 逻辑名:sh / cmd / powershell
|
|
||||||
ShellPath string `json:"shell_path,omitempty"` // 实际解释器路径(符号链接已解开)
|
|
||||||
ShellVer string `json:"shell_ver,omitempty"` // 版本首行(拿不到就留空)
|
|
||||||
Root string `json:"root,omitempty"`
|
|
||||||
|
|
||||||
// exec / kill
|
|
||||||
ID string `json:"id,omitempty"`
|
|
||||||
Cmd string `json:"cmd,omitempty"`
|
|
||||||
Cwd string `json:"cwd,omitempty"`
|
|
||||||
TimeoutMS int `json:"timeout_ms,omitempty"`
|
|
||||||
Env map[string]string `json:"env,omitempty"`
|
|
||||||
|
|
||||||
// chunk / exit
|
|
||||||
Stream []byte `json:"chunk,omitempty"` // 原始字节,JSON 里是 base64
|
|
||||||
Out string `json:"out,omitempty"` // "out" | "err"
|
|
||||||
Code *int `json:"code,omitempty"`
|
|
||||||
Killed string `json:"killed_by,omitempty"` // cancelled | timeout
|
|
||||||
MS int64 `json:"ms,omitempty"`
|
|
||||||
Err string `json:"err,omitempty"`
|
|
||||||
Truncated bool `json:"truncated,omitempty"`
|
|
||||||
|
|
||||||
// health(hub 请求 / 节点回报共用)
|
|
||||||
UptimeSec int64 `json:"uptime_sec,omitempty"` // 本进程已运行秒数
|
|
||||||
HostUptimeSec int64 `json:"host_uptime_sec,omitempty"` // 主机开机秒数(不支持为 -1)
|
|
||||||
Load1 float64 `json:"load1,omitempty"`
|
|
||||||
Load5 float64 `json:"load5,omitempty"`
|
|
||||||
Load15 float64 `json:"load15,omitempty"`
|
|
||||||
MemTotalMB int64 `json:"mem_total_mb,omitempty"`
|
|
||||||
MemFreeMB int64 `json:"mem_free_mb,omitempty"`
|
|
||||||
DiskTotalGB float64 `json:"disk_total_gb,omitempty"`
|
|
||||||
DiskFreeGB float64 `json:"disk_free_gb,omitempty"`
|
|
||||||
TempC float64 `json:"temp_c,omitempty"`
|
|
||||||
|
|
||||||
// file(read/write 共用一个 信封)
|
|
||||||
Op string `json:"op,omitempty"` // read | write
|
|
||||||
Path string `json:"path,omitempty"` // 设备侧绝对路径,必须在 root 内
|
|
||||||
Size int64 `json:"size,omitempty"` // 文件字节数
|
|
||||||
SHA string `json:"sha256,omitempty"` // 文件内容的 sha256(传完对账)
|
|
||||||
Data []byte `json:"data,omitempty"` // 数据块(JSON 里是 base64)
|
|
||||||
}
|
|
||||||
@@ -1,210 +0,0 @@
|
|||||||
// Package wsnode 是「节点主动出站 + 断线重连 + 心跳保活」的最小 WebSocket 基座。
|
|
||||||
// 语义与 files/print/agent 一致:节点在 NAT 后面也能被驱动,服务器不需要任何入站端口。
|
|
||||||
package wsnode
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"crypto/tls"
|
|
||||||
"crypto/x509"
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"log"
|
|
||||||
"net"
|
|
||||||
"net/http"
|
|
||||||
"net/url"
|
|
||||||
"os"
|
|
||||||
"os/exec"
|
|
||||||
"runtime"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/gorilla/websocket"
|
|
||||||
)
|
|
||||||
|
|
||||||
// ReadTimeout 多久没收到服务器任何消息(含 ping)就认定连接已死。
|
|
||||||
// hub 每 20s ping 一次,正常情况下永远触发不到;半开连接会在这里超时并触发重连。
|
|
||||||
const ReadTimeout = 90 * time.Second
|
|
||||||
|
|
||||||
type Config struct {
|
|
||||||
URL string // wss://host/ws
|
|
||||||
Token string // Authorization: Bearer <token>
|
|
||||||
Insecure bool // 跳过证书校验(自签环境)
|
|
||||||
CAFile string // 额外信任的 CA
|
|
||||||
FixClock bool // 证书校验失败时用服务器 Date 头校时(盒子无 RTC 时有用)
|
|
||||||
}
|
|
||||||
|
|
||||||
type Conn struct {
|
|
||||||
ws *websocket.Conn
|
|
||||||
mu chan struct{} // 容量 1 的信号量:gorilla 不允许并发写
|
|
||||||
cfg Config
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Conn) Send(v any) error {
|
|
||||||
b, err := json.Marshal(v)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
c.mu <- struct{}{}
|
|
||||||
defer func() { <-c.mu }()
|
|
||||||
return c.ws.WriteMessage(websocket.TextMessage, b)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Conn) Close() { _ = c.ws.Close() }
|
|
||||||
|
|
||||||
// Wrap 把已升级的底层连接包成 Conn(hub 服务端用;客户端走 Run/Dial)。
|
|
||||||
func Wrap(ws *websocket.Conn) *Conn {
|
|
||||||
ws.SetReadLimit(4 << 20)
|
|
||||||
return &Conn{ws: ws, mu: make(chan struct{}, 1)}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Run 持续维持连接:拨号 → onOpen → 读循环 → 断开 → 退避重连,直到 ctx 结束。
|
|
||||||
func Run(ctx context.Context, cfg Config, onOpen func(*Conn) error, onMsg func(*Conn, string, []byte)) error {
|
|
||||||
backoff := time.Second
|
|
||||||
for {
|
|
||||||
start := time.Now()
|
|
||||||
err := once(ctx, cfg, onOpen, onMsg)
|
|
||||||
if ctx.Err() != nil {
|
|
||||||
return ctx.Err()
|
|
||||||
}
|
|
||||||
// 稳定连过 60s 才把退避重置,避免「连上就断」时疯狂重试
|
|
||||||
if time.Since(start) > 60*time.Second {
|
|
||||||
backoff = time.Second
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
log.Printf("连接中断:%v;%s 后重连", err, backoff)
|
|
||||||
}
|
|
||||||
select {
|
|
||||||
case <-time.After(backoff):
|
|
||||||
case <-ctx.Done():
|
|
||||||
return ctx.Err()
|
|
||||||
}
|
|
||||||
if backoff < 30*time.Second {
|
|
||||||
backoff *= 2
|
|
||||||
if backoff > 30*time.Second {
|
|
||||||
backoff = 30 * time.Second
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func once(ctx context.Context, cfg Config, onOpen func(*Conn) error, onMsg func(*Conn, string, []byte)) error {
|
|
||||||
d := websocket.Dialer{
|
|
||||||
HandshakeTimeout: 15 * time.Second,
|
|
||||||
TLSClientConfig: tlsConf(cfg),
|
|
||||||
Proxy: http.ProxyFromEnvironment,
|
|
||||||
NetDial: (&net.Dialer{
|
|
||||||
Timeout: 15 * time.Second,
|
|
||||||
KeepAlive: 30 * time.Second,
|
|
||||||
}).Dial,
|
|
||||||
}
|
|
||||||
hdr := http.Header{}
|
|
||||||
if cfg.Token != "" {
|
|
||||||
hdr.Set("Authorization", "Bearer "+cfg.Token)
|
|
||||||
}
|
|
||||||
ws, resp, err := d.DialContext(ctx, cfg.URL, hdr)
|
|
||||||
if err != nil {
|
|
||||||
if resp != nil {
|
|
||||||
return fmt.Errorf("%s 拒绝连接:%s", cfg.URL, resp.Status)
|
|
||||||
}
|
|
||||||
if cfg.FixClock && !cfg.Insecure && isCertErr(err) {
|
|
||||||
log.Printf("证书校验失败,可能是系统时间不对(%v),尝试用服务器时间校准", err)
|
|
||||||
syncClock(cfg.URL)
|
|
||||||
}
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
defer ws.Close()
|
|
||||||
ws.SetReadLimit(4 << 20)
|
|
||||||
|
|
||||||
c := &Conn{ws: ws, mu: make(chan struct{}, 1), cfg: cfg}
|
|
||||||
if err := onOpen(c); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
for {
|
|
||||||
_ = ws.SetReadDeadline(time.Now().Add(ReadTimeout))
|
|
||||||
_, data, err := ws.ReadMessage()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
var head struct {
|
|
||||||
T string `json:"t"`
|
|
||||||
}
|
|
||||||
if json.Unmarshal(data, &head) != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
onMsg(c, head.T, data)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func isCertErr(err error) bool {
|
|
||||||
for _, k := range []string{"certificate", "x509", "tls:"} {
|
|
||||||
if contains(err.Error(), k) {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func contains(s, sub string) bool {
|
|
||||||
for i := 0; i+len(sub) <= len(s); i++ {
|
|
||||||
if s[i:i+len(sub)] == sub {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func tlsConf(cfg Config) *tls.Config {
|
|
||||||
t := &tls.Config{InsecureSkipVerify: cfg.Insecure}
|
|
||||||
if cfg.CAFile != "" {
|
|
||||||
if pem, err := os.ReadFile(cfg.CAFile); err == nil {
|
|
||||||
pool := x509.NewCertPool()
|
|
||||||
if pool.AppendCertsFromPEM(pem) {
|
|
||||||
t.RootCAs = pool
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
log.Printf("读 CA 失败:%v(忽略)", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return t
|
|
||||||
}
|
|
||||||
|
|
||||||
// syncClock 用服务器 Date 头把本机时间拨回来(只对 Linux 的 date 生效,Windows 一般有 RTC 不需要)。
|
|
||||||
// 证书本身可能是「因为时间错才失败」,所以这里刻意不校验证书。
|
|
||||||
func syncClock(rawURL string) {
|
|
||||||
u, err := url.Parse(rawURL)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
scheme := "http"
|
|
||||||
if u.Scheme == "wss" || u.Scheme == "https" {
|
|
||||||
scheme = "https"
|
|
||||||
}
|
|
||||||
req, err := http.NewRequest("HEAD", scheme+"://"+u.Host+"/", nil)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
client := &http.Client{
|
|
||||||
Timeout: 10 * time.Second,
|
|
||||||
Transport: &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}},
|
|
||||||
}
|
|
||||||
resp, err := client.Do(req)
|
|
||||||
if err != nil {
|
|
||||||
log.Printf("校时请求失败:%v", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer resp.Body.Close()
|
|
||||||
t, err := http.ParseTime(resp.Header.Get("Date"))
|
|
||||||
if err != nil {
|
|
||||||
log.Printf("服务器 Date 头不可解析:%v", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
log.Printf("本地时间偏差约 %s(服务器 %s)", time.Since(t).Truncate(time.Second), t.Format(time.RFC3339))
|
|
||||||
if runtime.GOOS == "windows" {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
out, err := exec.Command("date", "-u", "-s", t.UTC().Format("2006-01-02 15:04:05")).CombinedOutput()
|
|
||||||
if err != nil {
|
|
||||||
log.Printf("设置系统时间失败(需要 root):%v %s", err, out)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
log.Printf("已校时到 %s", t.UTC().Format(time.RFC3339))
|
|
||||||
}
|
|
||||||
@@ -1,48 +0,0 @@
|
|||||||
#!/bin/sh
|
|
||||||
# 交叉编译设备端二进制到 ./bin(纯本地动作:不联网、不推送、不依赖任何特定服务器)。
|
|
||||||
#
|
|
||||||
# sh scripts/build.sh # 编当前平台
|
|
||||||
# sh scripts/build.sh all # 编 linux-arm64 / linux-amd64 / linux-mips / windows-amd64 / darwin-amd64 / darwin-arm64
|
|
||||||
#
|
|
||||||
# 有本机 Go 就用本机;没有但有 docker 就用 golang 镜像;都没有就报错。
|
|
||||||
set -e
|
|
||||||
cd "$(dirname "$0")/.."
|
|
||||||
|
|
||||||
TARGETS="$(uname -s | tr 'A-Z' 'a-z')/$(uname -m | sed 's/x86_64/amd64/;s/aarch64/arm64/')"
|
|
||||||
[ "${1:-}" = "all" ] && TARGETS="linux/arm64 linux/amd64 linux/mips windows/amd64 darwin/amd64 darwin/arm64"
|
|
||||||
|
|
||||||
build_with_go() {
|
|
||||||
mkdir -p bin
|
|
||||||
for t in $TARGETS; do
|
|
||||||
os=${t%/*}; arch=${t#*/}; ext=""; gomips=""
|
|
||||||
[ "$os" = windows ] && ext=.exe
|
|
||||||
# mips 设备(OpenWrt / 老路由)基本都没有 FPU,硬浮点二进制一跑就是非法指令
|
|
||||||
[ "$arch" = mips ] && gomips=softfloat
|
|
||||||
echo "build $os/$arch"
|
|
||||||
GOOS=$os GOARCH=$arch GOMIPS=$gomips CGO_ENABLED=0 go build -trimpath -ldflags "-s -w" \
|
|
||||||
-o "bin/agent-device-$os-$arch$ext" ./cmd/agent
|
|
||||||
done
|
|
||||||
}
|
|
||||||
|
|
||||||
if command -v go >/dev/null 2>&1; then
|
|
||||||
build_with_go
|
|
||||||
elif command -v docker >/dev/null 2>&1; then
|
|
||||||
echo "本机没有 Go,改用 golang:1.23-alpine 容器编译"
|
|
||||||
docker run --rm -v "$PWD":/w -w /w \
|
|
||||||
-e CGO_ENABLED=0 -e TARGETS="$TARGETS" \
|
|
||||||
golang:1.23-alpine sh -c '
|
|
||||||
mkdir -p bin
|
|
||||||
for t in $TARGETS; do
|
|
||||||
os=${t%/*}; arch=${t#*/}; ext=""; gomips=""
|
|
||||||
[ "$os" = windows ] && ext=.exe
|
|
||||||
[ "$arch" = mips ] && gomips=softfloat
|
|
||||||
echo "build $os/$arch"
|
|
||||||
GOOS=$os GOARCH=$arch GOMIPS=$gomips go build -trimpath -ldflags "-s -w" \
|
|
||||||
-o "bin/agent-device-$os-$arch$ext" ./cmd/agent
|
|
||||||
done'
|
|
||||||
else
|
|
||||||
echo "需要 Go 或 docker 才能编译" >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
ls -lh bin
|
|
||||||
@@ -3,12 +3,6 @@ services:
|
|||||||
build: ./app
|
build: ./app
|
||||||
container_name: agent-core
|
container_name: agent-core
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
# 日志轮转:默认 json-file 无上限,长期跑会把磁盘吃穿。保留最近 100MB。
|
|
||||||
logging:
|
|
||||||
driver: json-file
|
|
||||||
options:
|
|
||||||
max-size: "20m"
|
|
||||||
max-file: "5"
|
|
||||||
ports:
|
ports:
|
||||||
# 直接把容器 8090 映射到宿主机端口,用 http://<服务器IP>:<AGENT_PORT> 访问。
|
# 直接把容器 8090 映射到宿主机端口,用 http://<服务器IP>:<AGENT_PORT> 访问。
|
||||||
- "${AGENT_PORT:-8090}:8090"
|
- "${AGENT_PORT:-8090}:8090"
|
||||||
@@ -34,9 +28,6 @@ services:
|
|||||||
# 对外地址:public_link 的默认值(scripts/init.sh 探测公网 IP 后写进 .env)。
|
# 对外地址:public_link 的默认值(scripts/init.sh 探测公网 IP 后写进 .env)。
|
||||||
# 设置页里填过 public_link.base_url 时以设置页为准。
|
# 设置页里填过 public_link.base_url 时以设置页为准。
|
||||||
- PUBLIC_BASE_URL=${PUBLIC_BASE_URL:-}
|
- PUBLIC_BASE_URL=${PUBLIC_BASE_URL:-}
|
||||||
# 设备接入(可选):设备主动连 wss://<公网前缀>/dev/ws 时的 Bearer token。
|
|
||||||
# 与 PUBLIC_BASE_URL 同时具备才会挂端点;留空 = 不启用,本地部署就是这种。
|
|
||||||
- DEVICE_TOKEN=${DEVICE_TOKEN:-}
|
|
||||||
networks:
|
networks:
|
||||||
- agent-mcp-net
|
- agent-mcp-net
|
||||||
|
|
||||||
|
|||||||
@@ -63,6 +63,63 @@ cd agent
|
|||||||
这个页面是纯静态文件(不用起服务),所以“node 都没装”的时候也能打开。重跑脚本会重新生成;
|
这个页面是纯静态文件(不用起服务),所以“node 都没装”的时候也能打开。重跑脚本会重新生成;
|
||||||
即使没自动弹出,文件也一直在那个路径。
|
即使没自动弹出,文件也一直在那个路径。
|
||||||
|
|
||||||
|
## Windows
|
||||||
|
|
||||||
|
需要 Node 20+(不需要 Docker,也不需要装 Git):
|
||||||
|
|
||||||
|
```bat
|
||||||
|
node local\start-win.mjs
|
||||||
|
node local\start-win.mjs --workspace=D:\AgentWork --port=8090
|
||||||
|
```
|
||||||
|
|
||||||
|
首次运行会:
|
||||||
|
|
||||||
|
1. 自检 Node 版本
|
||||||
|
2. **找命令执行环境**:优先用已装的 Git for Windows(自带 bash);没有再自动下载
|
||||||
|
[busybox-w32](https://frippery.org/busybox)(单文件约 600KB)到 `local/bin/busybox.exe`
|
||||||
|
3. 建工作目录(默认 `%USERPROFILE%\AgentWork`,`--workspace` 可改)下的 `tasks/` `data/` `skills/`
|
||||||
|
4. 生成 `local/config.win.yml`(**首次生成,之后永不覆盖**)
|
||||||
|
5. 把仓库 `skills/` 里的内置技能补过去(只补缺不覆盖)
|
||||||
|
6. `app/node_modules` 缺失时 `npm install`
|
||||||
|
7. 起 core 并守护(退出 3 秒后自动重启,连崩 5 次停)
|
||||||
|
|
||||||
|
浏览器开 `http://127.0.0.1:8090`,到「设置 → 模型池」加平台和 API Key。
|
||||||
|
**停止:Ctrl+C**(没有 `stop.sh`,启动器就是前台进程)。`--check` 只做自检不启动。
|
||||||
|
|
||||||
|
### 为什么 Windows 是另一条代码路径
|
||||||
|
|
||||||
|
`start.sh` 靠 `lsof` / `pgrep` / `readlink -f` / `nohup` / `setsid` / 进程组信号,Windows 一个都没有。
|
||||||
|
所以那 1100 多行 bash 没有移植,而是用 Node 重写了「启动器」这一层——它本来就只做进程管理,
|
||||||
|
不需要 shell。**业务代码一行都不分平台**:平台差异只落在两个文件里:
|
||||||
|
|
||||||
|
| 文件 | 负责 |
|
||||||
|
|---|---|
|
||||||
|
| `app/server/shell.js` | 用哪个 shell 跑命令、怎么杀进程树(POSIX 进程组 / Windows `taskkill /T`) |
|
||||||
|
| `local/start-win.mjs` | 探测、下载 busybox、生成配置、起进程、守护 |
|
||||||
|
|
||||||
|
### 覆盖与排错
|
||||||
|
|
||||||
|
| 变量 | 作用 |
|
||||||
|
|---|---|
|
||||||
|
| `AGENT_SHELL` | 直接指定 shell(绝对路径或 PATH 名),跳过一切探测 |
|
||||||
|
| `AGENT_SHELL_ARGS` | 参数模板,默认 `-c`(如 bash 想读 rc 可写 `-lc`) |
|
||||||
|
| `AGENT_GIT_BASH` | 指定 git-bash 位置(便携版/非标准安装路径) |
|
||||||
|
| `AGENT_BUSYBOX` | 指定 busybox.exe 位置 |
|
||||||
|
| `AGENT_BUSYBOX_URL` | 换 busybox 下载源(国内网络) |
|
||||||
|
|
||||||
|
命令到底交给了谁跑:启动日志里有一行 `terminal=...`,失败时会写成 `terminal=未找到(...)`。
|
||||||
|
|
||||||
|
### Windows 上仍有的限制
|
||||||
|
|
||||||
|
- **四个同栈 MCP 没有自动拉起**(配置里 `mcp_servers: []`):网页搜索/图片/视频/语音暂不可用,
|
||||||
|
`terminal`、文件工具、技能正常。
|
||||||
|
- **office 预览网关没起**:docx/xlsx/pptx 不能在线预览,但 `office` 技能生成文件不受影响。
|
||||||
|
- **没有沙箱**:和 macOS/Linux 本地模式一样,AI 的 `terminal` 就是你的 shell,能读写你有权限的任何文件。
|
||||||
|
工作目录选专用的,别选 `C:\` 或整个仓库。
|
||||||
|
- **`chmod` / `ln -s` 这类不生效**:Windows 没有 POSIX 权限位;模型写这类命令会“成功但什么都没做”。
|
||||||
|
- **`/tmp` 不是 Linux 的 `/tmp`**:busybox 会把它当当前盘根目录(`C:\tmp`),git-bash 映射到 `%TEMP%`。
|
||||||
|
模型最好用相对路径或会话目录。
|
||||||
|
|
||||||
## 可选能力
|
## 可选能力
|
||||||
|
|
||||||
| 能力 | 需要 | 没有时的表现 |
|
| 能力 | 需要 | 没有时的表现 |
|
||||||
|
|||||||
@@ -0,0 +1,324 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
// Windows 本机模式启动器(macOS / Linux 用 local/start.sh,两者注入同一组环境变量)。
|
||||||
|
//
|
||||||
|
// 为什么单独一个 Node 脚本:start.sh 那 1100 多行 bash 靠的是 lsof / pgrep / readlink -f /
|
||||||
|
// nohup / setsid / 进程组信号,Windows 一个都没有。与其在 Windows 上凑一套半残的 POSIX 环境,
|
||||||
|
// 不如用 Node 重写"启动器"这一层——它本来就只做进程管理,不需要 shell。
|
||||||
|
// 业务代码(app/server)一行都不分平台,平台差异只落在 app/server/shell.js 与这个文件里。
|
||||||
|
//
|
||||||
|
// 做的事,按顺序:
|
||||||
|
// 1. 自检(Node 20+)
|
||||||
|
// 2. 找 POSIX 命令执行环境:git-bash → 已有的 busybox-w32 → 都没有就下载 busybox-w32
|
||||||
|
// 3. 首次运行生成工作目录与 local/config.win.yml(之后永不覆盖)
|
||||||
|
// 4. 补技能(只补缺,不覆盖)
|
||||||
|
// 5. app/node_modules 缺失时 npm install
|
||||||
|
// 6. 拉起 core 并守护(退出自动重启)
|
||||||
|
//
|
||||||
|
// 用法:
|
||||||
|
// node local/start-win.mjs # 默认工作目录 %USERPROFILE%\AgentWork
|
||||||
|
// node local/start-win.mjs --workspace=D:\ai # 指定工作目录
|
||||||
|
// node local/start-win.mjs --check # 只做自检与探测,不启动
|
||||||
|
// node local/start-win.mjs --port=8090 --no-open
|
||||||
|
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import path from 'node:path';
|
||||||
|
import os from 'node:os';
|
||||||
|
import { spawn, spawnSync } from 'node:child_process';
|
||||||
|
import { createRequire } from 'node:module';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
|
const require = createRequire(import.meta.url);
|
||||||
|
const shellBackend = require('../app/server/shell.js');
|
||||||
|
|
||||||
|
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||||
|
const IS_WIN = process.platform === 'win32';
|
||||||
|
const BUSYBOX_PATH = path.join(ROOT, 'local', 'bin', 'busybox.exe');
|
||||||
|
const CONFIG_PATH = path.join(ROOT, 'local', 'config.win.yml');
|
||||||
|
|
||||||
|
// ---------- 小工具 ----------
|
||||||
|
const C = { ok: '\x1b[32m', warn: '\x1b[33m', err: '\x1b[31m', dim: '\x1b[2m', n: '\x1b[0m' };
|
||||||
|
const say = (s) => console.log(`${C.ok}==>${C.n} ${s}`);
|
||||||
|
const warn = (s) => console.log(`${C.warn}[!]${C.n} ${s}`);
|
||||||
|
const dim = (s) => console.log(`${C.dim} ${s}${C.n}`);
|
||||||
|
function die(s, hint) {
|
||||||
|
console.error(`${C.err}[x]${C.n} ${s}`);
|
||||||
|
if (hint) console.error(` ${hint}`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 参数 ----------
|
||||||
|
const opt = { workspace: '', port: 8090, open: true, check: false };
|
||||||
|
for (const a of process.argv.slice(2)) {
|
||||||
|
if (a.startsWith('--workspace=')) opt.workspace = a.slice('--workspace='.length);
|
||||||
|
else if (a.startsWith('--port=')) opt.port = Number(a.slice('--port='.length)) || 8090;
|
||||||
|
else if (a === '--no-open') opt.open = false;
|
||||||
|
else if (a === '--check') opt.check = true;
|
||||||
|
else if (a === '-h' || a === '--help') {
|
||||||
|
console.log('用法: node local/start-win.mjs [--workspace=<目录>] [--port=8090] [--no-open] [--check]');
|
||||||
|
process.exit(0);
|
||||||
|
} else die(`未知参数:${a}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 1. 自检 ----------
|
||||||
|
function checkNode() {
|
||||||
|
const major = Number(String(process.versions.node).split('.')[0]);
|
||||||
|
if (major < 20) die(`需要 Node.js 20+,当前 ${process.version}`, '装新版:https://nodejs.org/ 或 winget install OpenJS.NodeJS.LTS');
|
||||||
|
say(`Node ${process.version}(${process.arch})`);
|
||||||
|
if (!IS_WIN) warn('当前不是 Windows:这个启动器只是 Windows 用;macOS/Linux 请用 local/start.sh');
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 2. 命令执行环境 ----------
|
||||||
|
// 优先级由 app/server/shell.js 决定(AGENT_SHELL > 配置 > git-bash > busybox-w32)。
|
||||||
|
// 这里只负责"没有就补一个":装到 local/bin/busybox.exe,core 那边按固定路径探测得到。
|
||||||
|
async function ensureShell() {
|
||||||
|
shellBackend.reset();
|
||||||
|
const found = shellBackend.resolve({});
|
||||||
|
if (found) {
|
||||||
|
say(`命令执行环境:${shellBackend.describe({})}`);
|
||||||
|
return found;
|
||||||
|
}
|
||||||
|
if (!IS_WIN) die('找不到 POSIX shell(/bin/sh)', '这个启动器是 Windows 用的;macOS/Linux 用 local/start.sh');
|
||||||
|
|
||||||
|
warn('没有找到 POSIX shell(git-bash 与 busybox-w32 都不在)');
|
||||||
|
say('下载 busybox-w32(单文件,约 600KB,不需要管理员权限)');
|
||||||
|
await downloadBusybox();
|
||||||
|
|
||||||
|
shellBackend.reset();
|
||||||
|
const after = shellBackend.resolve({});
|
||||||
|
if (!after) die('busybox-w32 装好了但仍探测不到', `检查文件是否存在且可执行:${BUSYBOX_PATH}`);
|
||||||
|
say(`命令执行环境:${shellBackend.describe({})}`);
|
||||||
|
return after;
|
||||||
|
}
|
||||||
|
|
||||||
|
// busybox-w32 官方发布页永远指向同一个 busybox.exe;国内下载不顺时可自行换源。
|
||||||
|
// 全部候选都失败就明确报错并给出"手动放文件"的一步操作,不静默降级到 cmd.exe。
|
||||||
|
async function downloadBusybox() {
|
||||||
|
const urls = [];
|
||||||
|
if (process.env.AGENT_BUSYBOX_URL) urls.push(process.env.AGENT_BUSYBOX_URL);
|
||||||
|
urls.push('https://frippery.org/files/busybox/busybox.exe');
|
||||||
|
|
||||||
|
// 备用源:GitHub Release(release 资产名固定为 busybox.exe)。国内直连 GitHub 慢时
|
||||||
|
// 自动走 gh-proxy 前缀重试,两者都失败才放弃。
|
||||||
|
try {
|
||||||
|
const gh = await githubBusyboxUrl();
|
||||||
|
if (gh) urls.push(gh, 'https://gh-proxy.com/' + gh);
|
||||||
|
} catch (_) { /* 拿不到 latest 就只试官方源 */ }
|
||||||
|
|
||||||
|
fs.mkdirSync(path.dirname(BUSYBOX_PATH), { recursive: true });
|
||||||
|
const tmp = BUSYBOX_PATH + '.download';
|
||||||
|
let lastErr = '';
|
||||||
|
for (const u of urls) {
|
||||||
|
try {
|
||||||
|
process.stdout.write(` ${u}\n `);
|
||||||
|
await fetchToFile(u, tmp);
|
||||||
|
// 只读前两个字节校验 PE 头,不把整个文件读进内存。
|
||||||
|
const fd = fs.openSync(tmp, 'r');
|
||||||
|
const head = Buffer.alloc(2);
|
||||||
|
fs.readSync(fd, head, 0, 2, 0);
|
||||||
|
fs.closeSync(fd);
|
||||||
|
if (head.toString('latin1') !== 'MZ') throw new Error('下载到的不是 Windows 可执行文件(缺 MZ 头)');
|
||||||
|
fs.renameSync(tmp, BUSYBOX_PATH);
|
||||||
|
console.log('');
|
||||||
|
say(`已安装 ${BUSYBOX_PATH}`);
|
||||||
|
return;
|
||||||
|
} catch (e) {
|
||||||
|
lastErr = e.message;
|
||||||
|
console.log(` 失败:${e.message}`);
|
||||||
|
try { fs.unlinkSync(tmp); } catch (_) { /* 没下载成功就没有临时文件 */ }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
die('busybox-w32 下载失败:' + lastErr,
|
||||||
|
`手动下载 https://frippery.org/files/busybox/busybox.exe 存成 ${BUSYBOX_PATH} 后重跑本脚本;`
|
||||||
|
+ '或先装 Git for Windows(自带 bash,会被自动识别)');
|
||||||
|
}
|
||||||
|
|
||||||
|
async function githubBusyboxUrl() {
|
||||||
|
const r = await fetch('https://api.github.com/repos/rmyorston/busybox-w32/releases/latest', {
|
||||||
|
headers: { 'User-Agent': 'agent-local-launcher' },
|
||||||
|
signal: AbortSignal.timeout(8000),
|
||||||
|
});
|
||||||
|
if (!r.ok) return null;
|
||||||
|
const j = await r.json();
|
||||||
|
const asset = (j.assets || []).find(a => /busybox\.exe$/i.test(a.name));
|
||||||
|
return asset ? asset.browser_download_url : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 带进度地下载(内容长度已知时打百分比;不知道就只打字节数)。
|
||||||
|
async function fetchToFile(url, dest) {
|
||||||
|
const r = await fetch(url, {
|
||||||
|
headers: { 'User-Agent': 'agent-local-launcher' },
|
||||||
|
signal: AbortSignal.timeout(120000),
|
||||||
|
redirect: 'follow',
|
||||||
|
});
|
||||||
|
if (!r.ok) throw new Error(`HTTP ${r.status}`);
|
||||||
|
const total = Number(r.headers.get('content-length') || 0);
|
||||||
|
const out = fs.createWriteStream(dest);
|
||||||
|
let got = 0;
|
||||||
|
for await (const chunk of r.body) {
|
||||||
|
got += chunk.length;
|
||||||
|
if (!out.write(chunk)) await new Promise(res => out.once('drain', res));
|
||||||
|
if (total) process.stdout.write(`\r ${(got / 1024).toFixed(0)}KB / ${(total / 1024).toFixed(0)}KB`);
|
||||||
|
}
|
||||||
|
await new Promise((res, rej) => out.end(err => (err ? rej(err) : res())));
|
||||||
|
if (total && got !== total) throw new Error(`下载不完整(${got}/${total} 字节)`);
|
||||||
|
if (got < 200 * 1024) throw new Error(`文件太小(${got} 字节),大概率不是 busybox`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 3. 工作目录与配置 ----------
|
||||||
|
function ensureWorkspace() {
|
||||||
|
const ws = path.resolve(opt.workspace || path.join(os.homedir(), 'AgentWork'));
|
||||||
|
const dirs = {
|
||||||
|
root: ws,
|
||||||
|
tasks: path.join(ws, 'tasks'),
|
||||||
|
data: path.join(ws, 'data'),
|
||||||
|
skills: path.join(ws, 'skills'),
|
||||||
|
};
|
||||||
|
for (const d of [dirs.tasks, dirs.data, dirs.skills]) fs.mkdirSync(d, { recursive: true });
|
||||||
|
say(`工作目录:${ws}`);
|
||||||
|
return dirs;
|
||||||
|
}
|
||||||
|
|
||||||
|
function ensureConfig(dirs) {
|
||||||
|
if (fs.existsSync(CONFIG_PATH)) {
|
||||||
|
dim(`复用已有配置 ${CONFIG_PATH}(不会覆盖你在网页里改的模型与密钥)`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// YAML 里统一用正斜杠:Node 与 YAML 都不需要转义,反斜杠反而要写两遍。
|
||||||
|
const p = (s) => s.replace(/\\/g, '/');
|
||||||
|
const yml = `# 由 local/start-win.mjs 首次生成,之后不再覆盖。
|
||||||
|
# 字段含义与服务器版一致(见 app/config.example.yml),这里只列本机模式用到的部分。
|
||||||
|
port: ${opt.port}
|
||||||
|
|
||||||
|
# AI 的工作根:文件工具的根就是它,AI 看不到同级的 data/ 与 skills/。
|
||||||
|
workspace_root: "${p(dirs.tasks)}"
|
||||||
|
|
||||||
|
# SQLite(.agent.db)与启动 prompt dump。
|
||||||
|
data_root: "${p(dirs.data)}"
|
||||||
|
|
||||||
|
skills:
|
||||||
|
# 内置技能由启动器首次复制过来,之后只补缺不覆盖;pip 装的依赖落在同级的 deps/。
|
||||||
|
skills_root: "${p(dirs.skills)}"
|
||||||
|
|
||||||
|
# 留空:启动后到设置页添加平台与 API Key,再点「重启」(启动器负责把进程拉起来)。
|
||||||
|
platforms: []
|
||||||
|
|
||||||
|
log_level: info
|
||||||
|
|
||||||
|
# 同栈 MCP(网页搜索 / 图片 / 视频 / 语音)暂未由 Windows 启动器拉起,
|
||||||
|
# 需要时在设置页按卡片添加地址,或先用 local/start.sh 的机器上那份配置。
|
||||||
|
mcp_servers: []
|
||||||
|
`;
|
||||||
|
fs.writeFileSync(CONFIG_PATH, yml, 'utf8');
|
||||||
|
say(`已生成配置 ${CONFIG_PATH}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 4. 技能 ----------
|
||||||
|
// 只补缺不覆盖:用户改过的技能、自己新建的技能都不能被启动器冲掉(与 start.sh 同语义)。
|
||||||
|
function syncSkills(dirs) {
|
||||||
|
const src = path.join(ROOT, 'skills');
|
||||||
|
if (!fs.existsSync(src)) return;
|
||||||
|
let copied = 0;
|
||||||
|
for (const name of fs.readdirSync(src)) {
|
||||||
|
if (name === 'deps' || name.startsWith('.')) continue; // deps 是依赖层,按技能各自安装
|
||||||
|
const from = path.join(src, name);
|
||||||
|
const to = path.join(dirs.skills, name);
|
||||||
|
if (!fs.statSync(from).isDirectory() || fs.existsSync(to)) continue;
|
||||||
|
fs.cpSync(from, to, { recursive: true });
|
||||||
|
copied++;
|
||||||
|
}
|
||||||
|
say(copied ? `补齐技能 ${copied} 个` : '技能已是最新(不覆盖已有目录)');
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 5. 依赖 ----------
|
||||||
|
function ensureDeps() {
|
||||||
|
const appDir = path.join(ROOT, 'app');
|
||||||
|
if (fs.existsSync(path.join(appDir, 'node_modules', 'better-sqlite3'))) return;
|
||||||
|
warn('首次运行需要安装 Node 依赖(app/node_modules 缺失)');
|
||||||
|
const npm = IS_WIN ? 'npm.cmd' : 'npm';
|
||||||
|
const r = spawnSync(npm, ['install'], { cwd: appDir, stdio: 'inherit', shell: IS_WIN });
|
||||||
|
if (r.status !== 0) {
|
||||||
|
die('npm install 失败',
|
||||||
|
'国内网络可先换源:npm config set registry https://registry.npmmirror.com 后重试');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 6. 起 core 并守护 ----------
|
||||||
|
function envFor(shell, dirs) {
|
||||||
|
const deps = path.join(dirs.skills, 'deps');
|
||||||
|
fs.mkdirSync(deps, { recursive: true });
|
||||||
|
return {
|
||||||
|
...process.env,
|
||||||
|
PORT: String(opt.port),
|
||||||
|
HOST: '127.0.0.1', // 本机模式只听回环(与 start.sh 一致)
|
||||||
|
AGENT_CONFIG: CONFIG_PATH,
|
||||||
|
AGENT_FILE_SCOPE: 'workspace', // 文件工具的根放宽到工作目录(本地单用户形态)
|
||||||
|
AGENT_LOCAL_PICK: '1',
|
||||||
|
AGENT_IMAGE_INLINE: '1', // 回环地址厂商拉不到,读图改内联 base64
|
||||||
|
PYTHONPATH: deps,
|
||||||
|
AGENT_SKILLS_DEPS: deps,
|
||||||
|
// 启动器探测到的 shell 直接钉给 core:两边 PATH 可能略有差异,钉住可避免"启动器说
|
||||||
|
// 用 git-bash、core 里却探测成 busybox"这种难查的双份事实。
|
||||||
|
AGENT_SHELL: shell.cmd,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function openBrowser(url) {
|
||||||
|
if (!opt.open) return;
|
||||||
|
try {
|
||||||
|
if (IS_WIN) spawn('cmd', ['/c', 'start', '', url], { stdio: 'ignore', windowsHide: true, detached: true }).unref();
|
||||||
|
else if (process.platform === 'darwin') spawn('open', [url], { stdio: 'ignore', detached: true }).unref();
|
||||||
|
else spawn('xdg-open', [url], { stdio: 'ignore', detached: true }).unref();
|
||||||
|
} catch (_) { /* 打不开浏览器不影响服务 */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
function startCore(shell, dirs) {
|
||||||
|
const env = envFor(shell, dirs);
|
||||||
|
const appDir = path.join(ROOT, 'app');
|
||||||
|
let stopping = false;
|
||||||
|
let restarts = 0;
|
||||||
|
let child = null;
|
||||||
|
|
||||||
|
const launch = () => {
|
||||||
|
child = spawn(process.execPath, ['server/server.js'], { cwd: appDir, env, stdio: 'inherit' });
|
||||||
|
child.on('exit', (code) => {
|
||||||
|
if (stopping) return;
|
||||||
|
restarts++;
|
||||||
|
// 连续崩 5 次就停:多半是配置错(端口被占 / 模型池空),无限重启只会刷屏。
|
||||||
|
if (restarts > 5) die(`core 连续退出 5 次(最后退出码 ${code})`, '看上面的报错;常见原因:端口被占用、config.win.yml 写错');
|
||||||
|
warn(`core 退出了(code=${code}),3 秒后重启(第 ${restarts} 次)`);
|
||||||
|
setTimeout(launch, 3000);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const stop = () => {
|
||||||
|
stopping = true;
|
||||||
|
if (child && child.pid) shellBackend.killTree(child);
|
||||||
|
process.exit(0);
|
||||||
|
};
|
||||||
|
process.on('SIGINT', stop);
|
||||||
|
process.on('SIGTERM', stop);
|
||||||
|
|
||||||
|
launch();
|
||||||
|
const url = `http://127.0.0.1:${opt.port}`;
|
||||||
|
setTimeout(() => openBrowser(url), 1500);
|
||||||
|
say(`启动完成:${url}(Ctrl+C 停止)`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 主流程 ----------
|
||||||
|
(async () => {
|
||||||
|
checkNode();
|
||||||
|
const shell = await ensureShell();
|
||||||
|
const dirs = ensureWorkspace();
|
||||||
|
ensureConfig(dirs);
|
||||||
|
syncSkills(dirs);
|
||||||
|
|
||||||
|
if (opt.check) {
|
||||||
|
say('自检完成(--check 不启动服务)');
|
||||||
|
dim(`配置:${CONFIG_PATH}`);
|
||||||
|
dim(`命令执行环境:${shellBackend.describe({})}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
ensureDeps();
|
||||||
|
startCore(shell, dirs);
|
||||||
|
})();
|
||||||
+3
-8
@@ -4,7 +4,7 @@
|
|||||||
# ./scripts/init.sh # 已有 .env / config.yml 均不覆盖
|
# ./scripts/init.sh # 已有 .env / config.yml 均不覆盖
|
||||||
#
|
#
|
||||||
# 可选变量:PUBLIC_IP、AGENT_PORT、AUTH_USER / AUTH_PASSWORD(默认 admin / admin)、
|
# 可选变量:PUBLIC_IP、AGENT_PORT、AUTH_USER / AUTH_PASSWORD(默认 admin / admin)、
|
||||||
# EXECUTOR_TOKEN / WXBOT_TOKEN / DEVICE_TOKEN / AUTH_SECRET(不给则生成并复用)。
|
# EXECUTOR_TOKEN / WXBOT_TOKEN / AUTH_SECRET(不给则生成并复用)。
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
|
||||||
REPO_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
REPO_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||||
@@ -55,7 +55,6 @@ title "生成 $ENV_FILE"
|
|||||||
|
|
||||||
EXECUTOR_TOKEN="${EXECUTOR_TOKEN:-$(env_get EXECUTOR_TOKEN)}"
|
EXECUTOR_TOKEN="${EXECUTOR_TOKEN:-$(env_get EXECUTOR_TOKEN)}"
|
||||||
WXBOT_TOKEN="${WXBOT_TOKEN:-$(env_get WXBOT_TOKEN)}"
|
WXBOT_TOKEN="${WXBOT_TOKEN:-$(env_get WXBOT_TOKEN)}"
|
||||||
DEVICE_TOKEN="${DEVICE_TOKEN:-$(env_get DEVICE_TOKEN)}"
|
|
||||||
AUTH_SECRET="${AUTH_SECRET:-$(env_get AUTH_SECRET)}"
|
AUTH_SECRET="${AUTH_SECRET:-$(env_get AUTH_SECRET)}"
|
||||||
AGENT_PORT="${PORT_INPUT:-$(env_get AGENT_PORT)}"
|
AGENT_PORT="${PORT_INPUT:-$(env_get AGENT_PORT)}"
|
||||||
AGENT_PORT="${AGENT_PORT:-8090}"
|
AGENT_PORT="${AGENT_PORT:-8090}"
|
||||||
@@ -63,9 +62,6 @@ OLD_URL="$(env_get PUBLIC_BASE_URL)"
|
|||||||
|
|
||||||
EXECUTOR_TOKEN="${EXECUTOR_TOKEN:-$(gen_hex)}"
|
EXECUTOR_TOKEN="${EXECUTOR_TOKEN:-$(gen_hex)}"
|
||||||
WXBOT_TOKEN="${WXBOT_TOKEN:-$(gen_hex)}"
|
WXBOT_TOKEN="${WXBOT_TOKEN:-$(gen_hex)}"
|
||||||
# 设备接入(devices.js):设备连 wss://<公网前缀>/dev/ws 时出示的 Bearer token。
|
|
||||||
# 与 PUBLIC_BASE_URL 同时具备才启用;没公网地址的部署生成了也无害。
|
|
||||||
DEVICE_TOKEN="${DEVICE_TOKEN:-$(gen_hex)}"
|
|
||||||
AUTH_SECRET="${AUTH_SECRET:-$(gen_hex)}"
|
AUTH_SECRET="${AUTH_SECRET:-$(gen_hex)}"
|
||||||
|
|
||||||
if [ -n "$PUBLIC_IP" ]; then
|
if [ -n "$PUBLIC_IP" ]; then
|
||||||
@@ -88,7 +84,7 @@ fi
|
|||||||
EXTRAS=""
|
EXTRAS=""
|
||||||
if [ -f "$ENV_FILE" ]; then
|
if [ -f "$ENV_FILE" ]; then
|
||||||
EXTRAS="$(awk -F= '/^[A-Za-z_][A-Za-z0-9_]*=/ &&
|
EXTRAS="$(awk -F= '/^[A-Za-z_][A-Za-z0-9_]*=/ &&
|
||||||
$1 !~ /^(EXECUTOR_TOKEN|WXBOT_TOKEN|DEVICE_TOKEN|AUTH_SECRET|AGENT_PORT|PUBLIC_BASE_URL)$/ { print }' \
|
$1 !~ /^(EXECUTOR_TOKEN|WXBOT_TOKEN|AUTH_SECRET|AGENT_PORT|PUBLIC_BASE_URL)$/ { print }' \
|
||||||
"$ENV_FILE" || true)"
|
"$ENV_FILE" || true)"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
@@ -96,7 +92,6 @@ fi
|
|||||||
echo "# 由 scripts/init.sh 生成;重跑复用已有密钥,并保留其它变量。"
|
echo "# 由 scripts/init.sh 生成;重跑复用已有密钥,并保留其它变量。"
|
||||||
echo "EXECUTOR_TOKEN=$EXECUTOR_TOKEN"
|
echo "EXECUTOR_TOKEN=$EXECUTOR_TOKEN"
|
||||||
echo "WXBOT_TOKEN=$WXBOT_TOKEN"
|
echo "WXBOT_TOKEN=$WXBOT_TOKEN"
|
||||||
echo "DEVICE_TOKEN=$DEVICE_TOKEN"
|
|
||||||
echo "AUTH_SECRET=$AUTH_SECRET"
|
echo "AUTH_SECRET=$AUTH_SECRET"
|
||||||
echo "AGENT_PORT=$AGENT_PORT"
|
echo "AGENT_PORT=$AGENT_PORT"
|
||||||
echo "PUBLIC_BASE_URL=$PUBLIC_BASE_URL"
|
echo "PUBLIC_BASE_URL=$PUBLIC_BASE_URL"
|
||||||
@@ -106,7 +101,7 @@ fi
|
|||||||
fi
|
fi
|
||||||
} > "$ENV_FILE"
|
} > "$ENV_FILE"
|
||||||
|
|
||||||
info "EXECUTOR_TOKEN / WXBOT_TOKEN / DEVICE_TOKEN / AUTH_SECRET 已就位"
|
info "EXECUTOR_TOKEN / WXBOT_TOKEN / AUTH_SECRET 已就位"
|
||||||
|
|
||||||
# ---------- config.yml(只写初始管理员)----------
|
# ---------- config.yml(只写初始管理员)----------
|
||||||
title "检查 $CONFIG_YML"
|
title "检查 $CONFIG_YML"
|
||||||
|
|||||||
Reference in New Issue
Block a user