Compare commits
16
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
29e4690982 | ||
|
|
1eeaf38009 | ||
|
|
1fd04e2607 | ||
|
|
92f0f16070 | ||
|
|
0e2f7c219f | ||
|
|
1e7f3e76ee | ||
|
|
938a99cabe | ||
|
|
3c9f9d2bdb | ||
|
|
4a36cc0266 | ||
|
|
af2e4a1c20 | ||
|
|
4333a53dd3 | ||
|
|
7d855454a8 | ||
|
|
1859fe0d5b | ||
|
|
925cf18da9 | ||
|
|
54c33dd7f1 | ||
|
|
4ff8b93025 |
@@ -0,0 +1,48 @@
|
|||||||
|
name: agent-device release
|
||||||
|
|
||||||
|
# 只认设备端标签(agent-device-v0.1.0),不碰主项目的 v2.5.0 这类版本号。
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags:
|
||||||
|
- 'agent-device-v*'
|
||||||
|
|
||||||
|
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: ${{ github.ref_name }}
|
||||||
|
tag_name: ${{ 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 | `agent-device-linux-*` |
|
||||||
|
| macOS amd64 / arm64 | `agent-device-darwin-*` |
|
||||||
|
| Windows amd64 | `agent-device-windows-amd64.exe` |
|
||||||
|
|
||||||
|
不含 mips / mipsle(OpenWrt 等自行交叉编译:`GOARCH=mips GOMIPS=softfloat`)。
|
||||||
+3
-3
@@ -10,9 +10,6 @@ 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__/
|
||||||
@@ -25,3 +22,6 @@ 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,6 +10,9 @@
|
|||||||
`/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` 需重启,少数写盘接口例外);**单租户**(登录只把门,不做资源级授权)。
|
||||||
|
|
||||||
@@ -21,10 +24,11 @@
|
|||||||
| `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`(macOS/Linux)与 `start-win.mjs`(Windows)负责探测、装依赖、守护 | 独立于 compose,见 `docs/local-mode.md` |
|
| `local/` | **本地端启动器**:同一份代码跑在本机(不起 Docker / executor),`start.sh` 负责探测、装依赖、守护 | 独立于 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` | — |
|
||||||
@@ -49,6 +53,7 @@ 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
|
||||||
@@ -57,6 +62,8 @@ 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` 工具直接回“未启用”。
|
||||||
|
|
||||||
### 端口与网络(要改先看这里)
|
### 端口与网络(要改先看这里)
|
||||||
|
|
||||||
@@ -90,12 +97,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`、`ASR_URL`、`PREVIEW_PROXIES`、`EXECUTOR_LOG_LEVEL`、`WXBOT_LOG_LEVEL`、`ASR_LOG_LEVEL`。
|
`PUBLIC_BASE_URL`、`DEVICE_TOKEN`、`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` 走
|
||||||
@@ -103,7 +110,10 @@ 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. **定时任务**:`scheduler.js` 每 30s tick → 到期则先 `archiveHistory`(历史整体 `archived`,
|
3. **远端设备**:设备上的 `agent-device` 出站连 core `/dev/ws` → `devices.js` 维护连接表 →
|
||||||
|
模型调 `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` 通知。
|
||||||
|
|
||||||
## 数据与状态
|
## 数据与状态
|
||||||
@@ -133,7 +143,9 @@ 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. **工具 schema 是每轮全量重发的上下文成本**。新增工具前先读 `docs/tool-design.md`:能用已有工具
|
8. **设备是远端 shell**。`device exec` 在设备上就是 `sh -c` / `cmd /c`;`root` 只约束**起始
|
||||||
|
cwd**,命令里 `cd /etc` 照样能跑。`DEVICE_TOKEN` 泄漏等价于那台机器的 shell 泄漏,按这个等级管理。
|
||||||
|
9. **工具 schema 是每轮全量重发的上下文成本**。新增工具前先读 `docs/tool-design.md`:能用已有工具
|
||||||
的 `op` 扩展就不要新开工具。
|
的 `op` 扩展就不要新开工具。
|
||||||
|
|
||||||
## 开发与验证
|
## 开发与验证
|
||||||
@@ -204,6 +216,8 @@ 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,6 +41,29 @@ 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,7 +59,6 @@ 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` 字面量决定 |
|
||||||
@@ -404,9 +403,6 @@ 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,9 +33,6 @@ 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,6 +14,7 @@
|
|||||||
"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"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -2002,6 +2003,27 @@
|
|||||||
"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,6 +13,7 @@
|
|||||||
"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,9 +76,7 @@ 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.shell:跑命令用的 POSIX shell(空 = 自动探测:POSIX 直接 /bin/sh;Windows 依次找
|
terminal: { default_timeout_ms: 30000, max_output_chars: 10000 },
|
||||||
// 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 上的回合缓存不重抓。
|
||||||
|
|||||||
@@ -0,0 +1,448 @@
|
|||||||
|
// 设备(远端执行节点)接入层。
|
||||||
|
//
|
||||||
|
// 设备主动出站连 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 };
|
||||||
+16
-6
@@ -8,7 +8,6 @@ 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');
|
||||||
@@ -119,11 +118,19 @@ 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) {
|
||||||
return instanceId(cfg.data_root) + ':' + (session.user || '-') + ':' + session.id +
|
const n = session.history ? archivedCount(session.history) : archivedCountOf(session.id);
|
||||||
':' + archivedCount(session.history);
|
return instanceId(cfg.data_root) + ':' + (session.user || '-') + ':' + session.id + ':' + n;
|
||||||
}
|
}
|
||||||
|
|
||||||
function saveMessage(sessionId, msg) {
|
function saveMessage(sessionId, msg) {
|
||||||
@@ -569,8 +576,9 @@ 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; }
|
||||||
// 平台差异交给执行后端:POSIX 杀进程组,Windows 走 taskkill /T。
|
try { process.kill(-proc.pid, 'SIGKILL'); } catch (_) {
|
||||||
shell.killTree(proc);
|
try { proc.kill('SIGKILL'); } catch (__) {}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
run.procs.clear();
|
run.procs.clear();
|
||||||
}
|
}
|
||||||
@@ -885,7 +893,9 @@ 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 || '未知错误');
|
||||||
const errId = saveMessage(sessionId, { role: 'assistant', content: text });
|
// type='error_note':留痕给 UI,但不进模型上下文(buildMessages 跳过),
|
||||||
|
// 否则失败文案会当成模型的真实回复一直带下去。
|
||||||
|
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;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -310,6 +310,8 @@ 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()) {
|
||||||
|
|||||||
@@ -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,6 +49,11 @@ 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 不冲突)。
|
||||||
@@ -244,10 +249,6 @@ 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 失败不影响服务:只是核对用产物。
|
||||||
|
|||||||
@@ -1,226 +0,0 @@
|
|||||||
// 执行后端:全仓唯一处理「用哪个 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 };
|
|
||||||
@@ -205,12 +205,35 @@
|
|||||||
"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.",
|
"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": {
|
"parameters": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"required": ["op"],
|
"required": [
|
||||||
|
"op"
|
||||||
|
],
|
||||||
"properties": {
|
"properties": {
|
||||||
"op": { "type": "string", "enum": ["list", "set", "add", "remove"], "description": "list = read live profile; set = single-value honorific/industry; add/remove = preference tags." },
|
"op": {
|
||||||
"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." },
|
"type": "string",
|
||||||
"industry": { "type": "string", "description": "op=set: the user's industry/domain (≤20 chars, e.g. 金融). Pass empty string to clear." },
|
"enum": [
|
||||||
"tags": { "type": "array", "items": { "type": "string" }, "description": "op=add/remove: preference tag list, e.g. [\"偏好简洁回复\", \"图表中文标注\"]. Matching is exact text." }
|
"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."
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -340,11 +363,17 @@
|
|||||||
"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": ["op"],
|
"required": [
|
||||||
|
"op"
|
||||||
|
],
|
||||||
"properties": {
|
"properties": {
|
||||||
"op": {
|
"op": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"enum": ["list", "get", "run"],
|
"enum": [
|
||||||
|
"list",
|
||||||
|
"get",
|
||||||
|
"run"
|
||||||
|
],
|
||||||
"description": "Operation to perform on skills."
|
"description": "Operation to perform on skills."
|
||||||
},
|
},
|
||||||
"name": {
|
"name": {
|
||||||
@@ -403,6 +432,56 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"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": {
|
||||||
|
|||||||
@@ -5,12 +5,14 @@ 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 shell = require('../shell'); // 执行后端:shell 解析 + 进程树 kill(平台差异只在那边,这里不做分支)
|
const { spawn } = require('child_process');
|
||||||
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 profile = require('../user-profile'); // profile 工具的数据面(仅 llm/log 依赖,无环)
|
||||||
@@ -764,7 +766,7 @@ function selectOutput(text, head, tail) {
|
|||||||
return parts.join('\n\n');
|
return parts.join('\n\n');
|
||||||
}
|
}
|
||||||
|
|
||||||
// terminal:交执行后端起 shell(POSIX 默认 /bin/sh -c,Windows 由 shell.js 探测)+ 超时 + 输出截断
|
// terminal:spawn + 进程组 kill + 超时 + 输出截断
|
||||||
// 通用终端输出 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 时标记行原样保留(宁可见不丢数据)。
|
||||||
@@ -784,6 +786,116 @@ 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;
|
||||||
@@ -809,7 +921,7 @@ async function toolTerminal(ctx, args) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return new Promise((resolve) => {
|
return new Promise((resolve) => {
|
||||||
const child = shell.spawnShell(cfg, args.command, { cwd });
|
const child = spawn('/bin/sh', ['-c', args.command], { cwd, detached: true, env: process.env });
|
||||||
ctx.run.procs.add(child);
|
ctx.run.procs.add(child);
|
||||||
let out = '';
|
let out = '';
|
||||||
let killedBy = null; // 'timeout' | 'cancelled'
|
let killedBy = null; // 'timeout' | 'cancelled'
|
||||||
@@ -853,8 +965,10 @@ async function toolTerminal(ctx, args) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function killGroup(child) {
|
function killGroup(child) {
|
||||||
// 平台差异交给执行后端:POSIX 杀进程组,Windows 走 taskkill /T 杀进程树。
|
if (!child.pid) return;
|
||||||
shell.killTree(child);
|
try { process.kill(-child.pid, 'SIGKILL'); } catch (_) {
|
||||||
|
try { child.kill('SIGKILL'); } catch (__) {}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// fetch:抓取并转 Markdown。超时/取消覆盖到 body 读取完成(非仅响应头);
|
// fetch:抓取并转 Markdown。超时/取消覆盖到 body 读取完成(非仅响应头);
|
||||||
@@ -1787,6 +1901,7 @@ const HANDLERS = {
|
|||||||
profile: toolProfile,
|
profile: toolProfile,
|
||||||
recall: toolRecall,
|
recall: toolRecall,
|
||||||
db: toolDb,
|
db: toolDb,
|
||||||
|
device: toolDevice,
|
||||||
skill: toolSkill,
|
skill: toolSkill,
|
||||||
lab: toolLab,
|
lab: toolLab,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -14,7 +14,6 @@ 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');
|
||||||
|
|
||||||
@@ -188,8 +187,7 @@ function runEntry(ctx, entry, args, cwd, timeoutMs) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
// windowsHide:Windows 上 detached 之外的第二道保险,避免弹控制台;POSIX 忽略该选项。
|
const child = spawn(entry, args, { cwd, env: process.env, detached: true });
|
||||||
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;
|
||||||
@@ -202,7 +200,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);
|
||||||
shell.killTree(child);
|
try { process.kill(-child.pid, 'SIGKILL'); } catch (_) { try { child.kill('SIGKILL'); } catch (__) {} }
|
||||||
reject(new SkillExecutionError('技能执行超时(' + timeoutMs + 'ms)已终止:\n' + out.trim(), -1));
|
reject(new SkillExecutionError('技能执行超时(' + timeoutMs + 'ms)已终止:\n' + out.trim(), -1));
|
||||||
}, timeoutMs);
|
}, timeoutMs);
|
||||||
|
|
||||||
@@ -211,7 +209,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);
|
||||||
shell.killTree(child);
|
try { process.kill(-child.pid, 'SIGKILL'); } catch (_) { try { child.kill('SIGKILL'); } catch (__) {} }
|
||||||
reject(new SkillExecutionError('技能执行被用户终止', -1));
|
reject(new SkillExecutionError('技能执行被用户终止', -1));
|
||||||
}
|
}
|
||||||
}, 200);
|
}, 200);
|
||||||
|
|||||||
@@ -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') return '';
|
if (!m || m.type === 'errAck' || m.type === 'error_note') 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 = '【富文本消息,请到网页端查看】';
|
||||||
|
|||||||
@@ -0,0 +1,140 @@
|
|||||||
|
# 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`,会自动建) |
|
||||||
|
| `-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)。
|
||||||
@@ -0,0 +1,237 @@
|
|||||||
|
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)
|
||||||
|
}
|
||||||
@@ -0,0 +1,162 @@
|
|||||||
|
//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)
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
//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
|
||||||
|
}
|
||||||
@@ -0,0 +1,464 @@
|
|||||||
|
// 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"
|
||||||
|
|
||||||
|
"agent-device/pkg/proto"
|
||||||
|
"agent-device/pkg/wsnode"
|
||||||
|
)
|
||||||
|
|
||||||
|
const version = "0.1.0"
|
||||||
|
|
||||||
|
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 exe, err := os.Executable(); err == nil {
|
||||||
|
if real, err := filepath.EvalSymlinks(exe); err == nil {
|
||||||
|
exe = real
|
||||||
|
}
|
||||||
|
p := filepath.Join(filepath.Dir(exe), "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)
|
||||||
|
if err := os.MkdirAll(r.root, 0o755); err != nil {
|
||||||
|
log.Fatalf("工作根不可用:%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 := exec.CommandContext(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
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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
|
||||||
|
}
|
||||||
|
|
||||||
|
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"}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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 out []byte
|
||||||
|
switch name {
|
||||||
|
case "cmd":
|
||||||
|
out, _ = exec.CommandContext(ctx, "cmd", "/c", "ver").Output()
|
||||||
|
case "powershell", "pwsh":
|
||||||
|
out, _ = exec.CommandContext(ctx, bin, "-NoProfile", "-NonInteractive", "-Command",
|
||||||
|
"$PSVersionTable.PSVersion.ToString()").Output()
|
||||||
|
default:
|
||||||
|
out, _ = exec.CommandContext(ctx, p, "--version").Output()
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
//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)
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
//go:build windows
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"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
|
||||||
|
}
|
||||||
|
_ = exec.Command("taskkill", "/T", "/F", "/PID", strconv.Itoa(cmd.Process.Pid)).Run()
|
||||||
|
_ = cmd.Process.Kill()
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
module agent-device
|
||||||
|
|
||||||
|
go 1.22
|
||||||
|
|
||||||
|
require github.com/gorilla/websocket v1.5.3
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||||
|
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
// 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)
|
||||||
|
}
|
||||||
@@ -0,0 +1,210 @@
|
|||||||
|
// 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))
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# 交叉编译设备端二进制到 ./bin(纯本地动作:不联网、不推送、不依赖任何特定服务器)。
|
||||||
|
#
|
||||||
|
# sh scripts/build.sh # 编当前平台
|
||||||
|
# sh scripts/build.sh all # 编 linux-arm64 / linux-amd64 / 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 windows/amd64 darwin/amd64 darwin/arm64"
|
||||||
|
|
||||||
|
build_with_go() {
|
||||||
|
mkdir -p bin
|
||||||
|
for t in $TARGETS; do
|
||||||
|
os=${t%/*}; arch=${t#*/}; ext=""
|
||||||
|
[ "$os" = windows ] && ext=.exe
|
||||||
|
echo "build $os/$arch"
|
||||||
|
GOOS=$os GOARCH=$arch 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=""
|
||||||
|
[ "$os" = windows ] && ext=.exe
|
||||||
|
echo "build $os/$arch"
|
||||||
|
GOOS=$os GOARCH=$arch 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,6 +3,12 @@ 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"
|
||||||
@@ -28,6 +34,9 @@ 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,63 +63,6 @@ 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%`。
|
|
||||||
模型最好用相对路径或会话目录。
|
|
||||||
|
|
||||||
## 可选能力
|
## 可选能力
|
||||||
|
|
||||||
| 能力 | 需要 | 没有时的表现 |
|
| 能力 | 需要 | 没有时的表现 |
|
||||||
|
|||||||
@@ -1,324 +0,0 @@
|
|||||||
#!/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);
|
|
||||||
})();
|
|
||||||
+8
-3
@@ -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 / AUTH_SECRET(不给则生成并复用)。
|
# EXECUTOR_TOKEN / WXBOT_TOKEN / DEVICE_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,6 +55,7 @@ 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}"
|
||||||
@@ -62,6 +63,9 @@ 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
|
||||||
@@ -84,7 +88,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|AUTH_SECRET|AGENT_PORT|PUBLIC_BASE_URL)$/ { print }' \
|
$1 !~ /^(EXECUTOR_TOKEN|WXBOT_TOKEN|DEVICE_TOKEN|AUTH_SECRET|AGENT_PORT|PUBLIC_BASE_URL)$/ { print }' \
|
||||||
"$ENV_FILE" || true)"
|
"$ENV_FILE" || true)"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
@@ -92,6 +96,7 @@ 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"
|
||||||
@@ -101,7 +106,7 @@ fi
|
|||||||
fi
|
fi
|
||||||
} > "$ENV_FILE"
|
} > "$ENV_FILE"
|
||||||
|
|
||||||
info "EXECUTOR_TOKEN / WXBOT_TOKEN / AUTH_SECRET 已就位"
|
info "EXECUTOR_TOKEN / WXBOT_TOKEN / DEVICE_TOKEN / AUTH_SECRET 已就位"
|
||||||
|
|
||||||
# ---------- config.yml(只写初始管理员)----------
|
# ---------- config.yml(只写初始管理员)----------
|
||||||
title "检查 $CONFIG_YML"
|
title "检查 $CONFIG_YML"
|
||||||
|
|||||||
Reference in New Issue
Block a user