Author SHA1 Message Date
kicer 29e4690982 ci: GitHub Actions 按 agent-device-v* 标签编译并发布 Release
agent-device release / release (push) Waiting to run
2026-11-19 22:16:54 +08:00
kicer 1eeaf38009 docs: AGENTS.md / README.md 补 device 执行端(架构、端口、env、主链路、工具与约束) 2026-11-19 21:55:06 +08:00
kicer 1fd04e2607 chore: core 日志轮转 20m×5;device push 日志补本地文件名 2026-11-19 21:34:44 +08:00
kicer 92f0f16070 feat(device): 工具调用加日志(info 记动作/设备/耗时/命令截断)
exec/pull/push 记 info,失败升 warn,list/health 走 debug。
命令压成一行截断 120 字符,不记录 stdout/stderr 内容。
2026-11-19 21:32:49 +08:00
kicer 0e2f7c219f refactor(device): list 不再带 health 快照
那份值是设备上线时取的一次性快照,会随连接时长过期,放在 list 里容易被当成实时状态。
health 改为纯按需查询(action=health),list 只留设备身份与在线信息。
2026-11-19 19:50:20 +08:00
kicer 1e7f3e76ee fix(device): macOS 补上 uptime / load / 可用内存
darwin 分支原来只取内存总量,其余一律 -1。改为调 sysctl(kern.boottime /
vm.loadavg) 与 vm_stat;可用内存按 free+inactive+speculative 算(只看 free
会把缓存当占用,数字小得吓人)。温度需要 SMC,保持 -1。
2026-11-19 19:31:36 +08:00
kicer 938a99cabe perf(device): 大文件支持到 2GiB,超时改空闲判定
- 单文件上限 50MiB → 2GiB(两侧)
- pull 超时改成空闲看门狗:首块 30s,之后每块重置 30s,稳定但慢的链路不再被误杀
- pull 写盘背压:磁盘慢时 ws.pause(),drain 后 resume,结束时兜底恢复(否则连接会永久停住)
- push 改流式读 + 流式算 sha,不再整文件进内存;发完最后一包才等设备确认
2026-11-19 19:22:08 +08:00
kicer 3c9f9d2bdb feat(device): 文件通道 pull/push
core 与设备复用同一条 WS 搬文件:256KiB 分块、base64、50MiB 上限,
写盘先 .part 再校验 size/sha256 后 rename;device 工具新增 pull/push 两个动作。
2026-11-19 19:01:34 +08:00
kicer 4a36cc0266 feat(device): shell 支持配置绝对路径与 busybox,默认仍为 sh/cmd
不做自动探测(各系统 shell 变体太多,交给配置);配了路径就按 POSIX 语义 -c 执行,
busybox 走 sh -c;上报给 core 的 shell 归成短标签(bash/busybox/sh/cmd/powershell)。
2026-11-19 18:16:32 +08:00
kicer af2e4a1c20 refactor(device): 二进制改名 agent-device,默认读同目录 config.json
- 输出名 agent-device-<os>-<arch>,避免和仓库名/agent-core 在 ps 里混淆
- 不带 -config 时自动加载可执行文件同目录的 config.json(存在才读)
- 启动日志打印实际加载的配置文件路径
2026-11-19 17:31:21 +08:00
kicer 4333a53dd3 feat(device): 设备端源码独立成 device/,可脱离具体服务器编译运行
- 模块名去掉私有域名(agent-device),import 路径中性化
- 二进制不内置任何服务器地址与 token,-server 必填
- 新增 -config:token 可放 JSON 文件,避免 ps 泄露
- scripts/build.sh 只做本地构建(有 Go 用 Go,没 Go 用 docker 镜像)
- README 面向使用者,部署细节不进仓库
2026-11-19 17:21:12 +08:00
kicer 7d855454a8 refactor(device): 去掉 caps,shell 改报路径与版本
能力清单会过期且探测不可靠(Store stub、非登录 shell 的 PATH 差异),
交给模型现场自查;shell 是命令入口,补 shell_path/shell_ver。
2026-11-19 16:56:51 +08:00
kicer 1859fe0d5b feat(init): init.sh 生成并复用 DEVICE_TOKEN(设备接入用) 2026-11-19 16:42:01 +08:00
kicer 925cf18da9 chore(compose): core 注入 DEVICE_TOKEN(可选,留空不启用设备接入) 2026-11-19 16:38:25 +08:00
kicer 54c33dd7f1 feat(device): 新增 device 工具,远端设备执行 list/health/exec
设备主动出站连 wss://<公网前缀>/dev/ws,core 维护连接表;本地无公网前缀或未配
DEVICE_TOKEN 时端点不挂,行为与原来一致。
2026-11-19 16:37:49 +08:00
kicer 4ff8b93025 fix(engine): 增量上下文作废按 sessionId 现查,修复编辑后仍发增量
getSession() 只查 sessions 表,返回对象没有 history 字段,contextIdOf 里 archivedCount(session.history) 恒得 0。编辑/删除/清空四处入口的 invalidateContext 于是全作用在 "…:0" 上,压缩过的会话真实 cid(如 "…:3031")从没被作废,编辑完仍旧发增量,relay 缓存里留着已删除的行,上游随即 tool_call_mismatch。

改为拿不到 history 时按 sessionId 现查 count(type='archived');runLoop 热路径仍走内存计数。另把「模型调用失败」文案落库标为 type='error_note':buildMessages 跳过、微信不外发,避免失败文案被当成模型回复带进后续轮次。
2026-11-19 15:42:48 +08:00
27 changed files with 2246 additions and 18 deletions
+48
View File
@@ -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
View File
@@ -22,3 +22,6 @@ app/server/version.json
# 部署配置真身(含密钥,模板见 scripts/deploy.conf.example);
deploy.conf
relay/config.json
# 设备端编译产物(交叉编译后本地生成,不入库)
device/bin/
+18 -4
View File
@@ -10,6 +10,9 @@
`/chat/completions`)→ 模型调用内置工具 / MCP / 技能 → 命令在 `agent-executor` 隔离容器里执行 →
产物落在会话工作目录并回传。每个会话 = 一个真实 Linux 工作目录 + 一条 SQLite 会话记录。
另有一个可选的**设备执行端** `device/`:设备主动出站连 core 的 `/dev/ws`,模型用 `device`
工具在远端机器(Mac / Windows / OpenWrt 盒子)上跑命令、拉推文件。
设计基调:**单进程内存模型 + SQLite 同步 API**(JS 单线程,不存在跨进程竞争);**配置冷加载**
(改 `config.yml` 需重启,少数写盘接口例外);**单租户**(登录只把门,不做资源级授权)。
@@ -21,6 +24,7 @@
| `app/server/` | 后端全部代码(入口 `server.js`) | 见 `app/AGENTS.md` |
| `app/server/public/` | 前端静态资源,经典脚本按序加载,共享全局作用域 | 无构建步骤 |
| `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` |
| `mcp/` | 同栈 MCP 服务:`web_search` / `image_task` / `video_task` / `asr` | 四个容器,仅内网 |
| `skills/` | 目录式技能(`SKILL.md` + `run.py`/`run.sh`) | 运行时挂载,`skills/deps` 为依赖层 |
@@ -49,6 +53,7 @@ flowchart TD
CORE --> EXEC["agent-executor(9000 exec / 3100 预览,仅内网)"]
CORE --> MCP["mcp_web_search / mcp_image_task / mcp_video_task / mcp_asr(3000,仅内网)"]
CORE -->|"分段投递回复"| WXBOT
DEV["设备:Mac / Windows / OpenWrt"] -->|"wss 出站 /dev/ws"| CORE
```
- **对外只暴露 `agent-core` 一个端口**(宿主 `AGENT_PORT`,默认 8090)。executor、wxbot、MCP
@@ -57,6 +62,8 @@ flowchart TD
- 容器间按容器名访问(`http://agent-executor:9000`、`http://mcp_web_search:3000/`);
所有业务容器同在 `agent-mcp-net`(compose 里固定网络名,避免被加上项目名前缀)。
- `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)
`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**,只在其缺失时创建
最小骨架)。语音识别的上游 key/base/model 不在 env,
写在 `config.yml` 的 `mcp_servers[name=asr].headers`(容器不存平台密钥)。
## 三条主链路
## 四条主链路
1. **Web / HTTP**:`app/server/server.js` 装配 → 路由 → `engine.js` 起回合 →
`llm.js` 组装并流式调用上游 → `tools/executor.js` 执行工具(`terminal` / `skill` 走
@@ -103,7 +110,10 @@ flowchart TD
2. **微信**:`agent-wxbot` 收消息 → 回调 core `/wxhook/inbox` → `wechat.js` 落媒体、注入上下文 →
`routes/channel.js` 的命令层(`/new` `/switch` `/think` …)→ 同一套 `engine`;回合结束由
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` 通知。
## 数据与状态
@@ -133,7 +143,9 @@ flowchart TD
「回合中会话数 → 在用会话数 → 最久未用」择优(详见 `app/AGENTS.md`)。
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` 扩展就不要新开工具。
## 开发与验证
@@ -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/public/js/voice.js`(录音与插入)+ `app/server/routes/asr.js`(代理)+ `mcp/asr/`(转写);客户端桥契约见 `docs/voice-input.md` |
| 改隔离执行 | `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`(本地服务映射) |
| 加同栈 MCP 服务 | `mcp/<name>/` + `docker-compose.yml` + `config.yml` 的 `mcp_servers` |
| 加技能 | `skills/<name>/`(`SKILL.md` + `run.py`),见 `skills/README.md` |
+23
View File
@@ -41,6 +41,29 @@ macOS / Linux,Node 20+,不需要 Docker:
| [`skills/`](skills/README.md) | 内置技能 |
| [`local/`](local/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)。
## 配置
+22
View File
@@ -14,6 +14,7 @@
"multer": "1.4.5-lts.1",
"sharp": "0.35.4",
"turndown": "7.2.0",
"ws": "^8.23.0",
"yaml": "2.6.1"
}
},
@@ -2002,6 +2003,27 @@
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
"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": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",
+1
View File
@@ -13,6 +13,7 @@
"multer": "1.4.5-lts.1",
"sharp": "0.35.4",
"turndown": "7.2.0",
"ws": "^8.23.0",
"yaml": "2.6.1"
}
}
+448
View File
@@ -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 };
+13 -3
View File
@@ -118,11 +118,19 @@ function archivedCount(history) {
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>。
// 删除消息后要把这个 key 作废,让下一轮走全量重建。
// runLoop 里 session.history 已就绪,走内存计数;其余入口现查库,两条路结果一致。
function contextIdOf(session) {
return instanceId(cfg.data_root) + ':' + (session.user || '-') + ':' + session.id +
':' + archivedCount(session.history);
const n = session.history ? archivedCount(session.history) : archivedCountOf(session.id);
return instanceId(cfg.data_root) + ':' + (session.user || '-') + ':' + session.id + ':' + n;
}
function saveMessage(sessionId, msg) {
@@ -885,7 +893,9 @@ async function runLoopInner(sessionId, run) {
if (run.cancelled) break;
if (!result) {
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() });
break;
}
+2
View File
@@ -310,6 +310,8 @@ function buildMessages(session, language, mintUrl, profile, withProfile, trimOn)
history.forEach((row, i) => {
// archived:UI 可见,但不进入模型上下文(节省 token)
if (row.type === 'archived') return;
// error_note:失败文案,只给 UI 留痕,不进模型(否则被当成模型的真实回复带下去)
if (row.type === 'error_note') return;
// summarize_request(旧版遗留行):仅在未收尾的旧压缩回合内发给模型,其余一律跳过
if (row.type === 'summarize_request') {
if (i > lastClosingAssistant && (row.content || '').trim()) {
+6
View File
@@ -13,6 +13,7 @@ const scheduler = require('./scheduler');
const wechat = require('./wechat');
const llm = require('./llm');
const mcp = require('./mcp');
const devices = require('./devices');
const skills = require('./tools/skills');
const log = require('./log');
@@ -48,6 +49,11 @@ wechat.init(cfg, db, bus);
const app = express();
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 只挂内网)。必须挂在全局 express.json(2mb) 之前:媒体 base64 转发体远超 2mb,
// 由 hookRouter 自带的 32mb 解析器先读掉并置 req._body,下游全局 json 解析器自动跳过(同 executor 不冲突)。
+86 -7
View File
@@ -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.",
"parameters": {
"type": "object",
"required": ["op"],
"required": [
"op"
],
"properties": {
"op": { "type": "string", "enum": ["list", "set", "add", "remove"], "description": "list = read live profile; set = single-value honorific/industry; add/remove = preference tags." },
"honorific": { "type": "string", "description": "op=set: how to address the user (≤20 chars, e.g. 王工). Pass empty string to clear. Exactly one of honorific/industry per call." },
"industry": { "type": "string", "description": "op=set: the user's industry/domain (≤20 chars, e.g. 金融). Pass empty string to clear." },
"tags": { "type": "array", "items": { "type": "string" }, "description": "op=add/remove: preference tag list, e.g. [\"偏好简洁回复\", \"图表中文标注\"]. Matching is exact text." }
"op": {
"type": "string",
"enum": [
"list",
"set",
"add",
"remove"
],
"description": "list = read live profile; set = single-value honorific/industry; add/remove = preference tags."
},
"honorific": {
"type": "string",
"description": "op=set: how to address the user (≤20 chars, e.g. 王工). Pass empty string to clear. Exactly one of honorific/industry per call."
},
"industry": {
"type": "string",
"description": "op=set: the user's industry/domain (≤20 chars, e.g. 金融). Pass empty string to clear."
},
"tags": {
"type": "array",
"items": {
"type": "string"
},
"description": "op=add/remove: preference tag list, e.g. [\"偏好简洁回复\", \"图表中文标注\"]. Matching is exact text."
}
}
}
}
@@ -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.",
"parameters": {
"type": "object",
"required": ["op"],
"required": [
"op"
],
"properties": {
"op": {
"type": "string",
"enum": ["list", "get", "run"],
"enum": [
"list",
"get",
"run"
],
"description": "Operation to perform on skills."
},
"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",
"function": {
+113
View File
@@ -11,6 +11,8 @@ const skills = require('./skills');
const Database = require('better-sqlite3'); // db 工具:会话目录下的 data.db(同步 API,与单进程模型契合)
const TurndownService = require('turndown'); // fetch 工具:HTML→Markdown 用真解析器(内置 htmlparser2,容错截断/畸形文档)
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 scheduler = require('../scheduler'); // 只依赖 log/cron-parser/time.js,不成环(engine→executor→scheduler 单向)
const profile = require('../user-profile'); // profile 工具的数据面(仅 llm/log 依赖,无环)
@@ -784,6 +786,116 @@ function drainUiCards(text, ctx) {
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) {
const cfg = ctx.cfg;
const timeout = args.timeout_ms || cfg.terminal.default_timeout_ms;
@@ -1789,6 +1901,7 @@ const HANDLERS = {
profile: toolProfile,
recall: toolRecall,
db: toolDb,
device: toolDevice,
skill: toolSkill,
lab: toolLab,
};
+1 -1
View File
@@ -489,7 +489,7 @@ function getTurn(bid) { return turnState.get(bid) || resetTurn(bid); }
// 投递前的内容归一(语义同旧 deliverNow):errAck / 空文本 → 不可投;富文本 blocks → 占位文案。
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();
if (!content) return '';
if (content.startsWith('{"__blocks__"')) content = '【富文本消息,请到网页端查看】';
+140
View File
@@ -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)。
+237
View File
@@ -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)
}
+162
View File
@@ -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)
}
+67
View File
@@ -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
}
+464
View File
@@ -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
}
+21
View File
@@ -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)
}
+24
View File
@@ -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()
}
+5
View File
@@ -0,0 +1,5 @@
module agent-device
go 1.22
require github.com/gorilla/websocket v1.5.3
+2
View File
@@ -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=
+68
View File
@@ -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)
}
+210
View File
@@ -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))
}
+45
View File
@@ -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
+9
View File
@@ -3,6 +3,12 @@ services:
build: ./app
container_name: agent-core
restart: unless-stopped
# 日志轮转:默认 json-file 无上限,长期跑会把磁盘吃穿。保留最近 100MB。
logging:
driver: json-file
options:
max-size: "20m"
max-file: "5"
ports:
# 直接把容器 8090 映射到宿主机端口,用 http://<服务器IP>:<AGENT_PORT> 访问。
- "${AGENT_PORT:-8090}:8090"
@@ -28,6 +34,9 @@ services:
# 对外地址:public_link 的默认值(scripts/init.sh 探测公网 IP 后写进 .env)。
# 设置页里填过 public_link.base_url 时以设置页为准。
- PUBLIC_BASE_URL=${PUBLIC_BASE_URL:-}
# 设备接入(可选):设备主动连 wss://<公网前缀>/dev/ws 时的 Bearer token。
# 与 PUBLIC_BASE_URL 同时具备才会挂端点;留空 = 不启用,本地部署就是这种。
- DEVICE_TOKEN=${DEVICE_TOKEN:-}
networks:
- agent-mcp-net
+8 -3
View File
@@ -4,7 +4,7 @@
# ./scripts/init.sh # 已有 .env / config.yml 均不覆盖
#
# 可选变量: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
REPO_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
@@ -55,6 +55,7 @@ title "生成 $ENV_FILE"
EXECUTOR_TOKEN="${EXECUTOR_TOKEN:-$(env_get EXECUTOR_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)}"
AGENT_PORT="${PORT_INPUT:-$(env_get AGENT_PORT)}"
AGENT_PORT="${AGENT_PORT:-8090}"
@@ -62,6 +63,9 @@ OLD_URL="$(env_get PUBLIC_BASE_URL)"
EXECUTOR_TOKEN="${EXECUTOR_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)}"
if [ -n "$PUBLIC_IP" ]; then
@@ -84,7 +88,7 @@ fi
EXTRAS=""
if [ -f "$ENV_FILE" ]; then
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)"
fi
@@ -92,6 +96,7 @@ fi
echo "# 由 scripts/init.sh 生成;重跑复用已有密钥,并保留其它变量。"
echo "EXECUTOR_TOKEN=$EXECUTOR_TOKEN"
echo "WXBOT_TOKEN=$WXBOT_TOKEN"
echo "DEVICE_TOKEN=$DEVICE_TOKEN"
echo "AUTH_SECRET=$AUTH_SECRET"
echo "AGENT_PORT=$AGENT_PORT"
echo "PUBLIC_BASE_URL=$PUBLIC_BASE_URL"
@@ -101,7 +106,7 @@ fi
fi
} > "$ENV_FILE"
info "EXECUTOR_TOKEN / WXBOT_TOKEN / AUTH_SECRET 已就位"
info "EXECUTOR_TOKEN / WXBOT_TOKEN / DEVICE_TOKEN / AUTH_SECRET 已就位"
# ---------- config.yml(只写初始管理员)----------
title "检查 $CONFIG_YML"