mirror of
https://gitcode.com/JianFeeeee/HomeAgent.git
synced 2026-09-26 20:33:15 +00:00
用户要求:外部只装 HomeAgent 即可使用自带反代能力;用户只需穿透一个
webui 端口就能访问所有内部插件服务;认证与 WebSocket 支持都作为插件
的可声明项;插件 UI 要有可直接点击的入口。
实测 huawei_smarthome 插件的前端用**根绝对路径**(api('/api/status') →
fetch('/api/status'))。挂在 /p/<name>/ 这类路径前缀下,这些请求会打到
HomeAgent 自己的 /api/status —— 静默错路由;做 HTML/JS 内容重写对拼进
JS 字符串的绝对路径只是"按概率能用",会产生"页面能开、某个按钮就坏"的
静默故障。子域路由下根路径天然正确,**插件前端零改动**。
且它天然匹配"只穿透一个端口":webui 监听 0.0.0.0:8080 按 Host 分发,
外层 frp 单端口 TCP 隧道**一行都不用改**。
默认基座 localhost:RFC 6761 规定 *.localhost 强制解析到 loopback,
现代浏览器原生支持 ⇒ <标签>.localhost:8080 **零配置可用**,不需要 DNS、
证书、/etc/hosts。远程部署改 base_domain 即可。
- 外部插件 → plugin.json 的 proxies(静态可发现:插件没起来也能报
"声明了 ui 但目标不可达",而不是静默 404)
- 内置插件 → s.DeclareProxy()(remotedevice 是内置的、没有 plugin.json,
却最需要被反代出去)
反代层在 webui 侧读清单:webui 已能拿到插件目录(PluginManager.PluginDir),
因此**无需给内核接口加方法**。manifest 解析忽略未知字段,加 proxies 对
"旧内核读新插件"与"新内核读旧插件"都无害。
新增 sdk/ProxyDecl 与配套校验(ValidProxyAuth / ValidProxyHostLabel /
NormalizeProxyHost / ValidateProxyDecl);新增运行期 ProxyDeclarer 通道。
hmapdev 的 writePluginJSON 是**白名单 map 重建**——不同步加字段会让声明
被打包静默丢弃(插件作者本地正常、装上去失效),因此 PlgConfig 与
writePluginJSON 同时加,并在打包前校验声明(插件作者本地就能发现写错)。
auth=homeagent(默认,安全的默认):门户会话 / X-API-Key / ?__token=;
auth=none:信任上游自身鉴权,供设备与嵌入式客户端使用——它们不可能持有
浏览器会话,强制走门户鉴权会把设备链路挡死。remotedevice 声明 none,
因为它自身用 ws_token 强制校验。
未声明时升级请求**明确拒绝**(400 + 原因),而不是静默降级成普通请求
(后者表现为前端不断重连、日志看不出原因)。
1. 不跟随上游 3xx:旧实现用 http.DefaultClient(默认跟最多 10 跳),
上游 302 到内网地址时反代自己跟过去、失败回 502 并把内网 URL 泄给
客户端。httputil.ReverseProxy 默认不跟随,3xx 原样透传。
2. 逐帧 flush:旧实现 io.Copy 导致上游流式响应被缓冲到上游关闭才下发
(实测 3 帧 200ms 间隔的流,客户端在 +600ms 一次性收到全部)。
设 FlushInterval=-1。
另补齐 X-Forwarded-For/Host/Proto(旧实现完全不注入,上游无法判断真实
来源),并剥掉上游 Set-Cookie 的 Domain(防止插件 cookie 打到主门户域)。
插件页新增「服务入口」卡片:列出全部被反代的插件服务(含被拒条目与
不可达原因),点「打开」直接访问。链接带 ?__token=<api_key>,因为子域
与门户不同源、浏览器不会自动带会话 cookie。
webui +35 条、SDK +4 条、工具链 +4 条。关键几条:
- 根绝对路径必须原样到上游(选 Host 路由的核心理由)
- 上游 302 必须原样透传、且反代不得跟随(旧缺陷)
- 已知 Content-Length 的慢速响应必须逐帧到达(**这条经过变异验证**:
把 FlushInterval 改回 0 后判据挂死 → FAIL,还原后回绿。
说明:最初写的 SSE/chunked 版本是假判据——ReverseProxy 对
text/event-stream 与 ContentLength=-1 会自动立即 flush,与
FlushInterval 无关,变异抓不到,已改正)
- 子域标签冲突不得静默覆盖(后者保留可见并带原因)
- 非法声明不进路由但必须可见(配置页要能看到原因)
- 未声明 websocket 的升级请求必须 400
- auth 逐条生效:none 放行匿名、homeagent 与默认档 401 且给可操作提示
- 自动发现:显式 host 不得被自动编号覆盖(**测试抓到的真 bug**:
remotedevice 声明的 "devices" 会被改成 "devices-2" 而静默失效)
- 真实端到端:生产实例 huawei_smarthome 的 UI(9444 字节)与其
/api/status 经反代正确透传
go build ./... 通过;相关包全量测试通过。
internal/plugin/proc 的 TestStreaming_PublishLatencyFlatAcrossSubscribers
是**预存在的不稳定测试**(同一份代码 10 次跑 9 过 1 败,且本改动完全
未触及该包),非本次引入。
364 lines
13 KiB
Go
364 lines
13 KiB
Go
package remotedevice
|
||
|
||
import (
|
||
"context"
|
||
"crypto/rand"
|
||
"encoding/hex"
|
||
"encoding/json"
|
||
"fmt"
|
||
"log"
|
||
"net"
|
||
"net/http"
|
||
"path/filepath"
|
||
"strings"
|
||
"sync"
|
||
"time"
|
||
|
||
"gitcode.com/JianFeeeee/HomeAgent/internal/plugin"
|
||
sdk "gitcode.com/JianFeeeee/HomeAgent/internal/sdk"
|
||
)
|
||
|
||
func init() {
|
||
plugin.RegisterPluginMeta("remotedevice", "远程设备网关", "Remote Device")
|
||
plugin.RegisterFactory("remotedevice", func(name string, config map[string]interface{}) (sdk.Plugin, error) {
|
||
return New(name), nil
|
||
})
|
||
}
|
||
|
||
const defaultAddr = "127.0.0.1:9890"
|
||
|
||
// Plugin 是 remotedevice 设备接入网关插件:
|
||
// 持有 HTTP 服务(WS 设备通道 + REST 管理面)与 devicectl Device(agent 工具)。
|
||
type Plugin struct {
|
||
name string
|
||
registry *Registry
|
||
mux *http.ServeMux
|
||
server *http.Server
|
||
addr string
|
||
token string
|
||
sdk *sdk.PluginSDK
|
||
dev *devicectlDevice
|
||
|
||
// devChansMu/devChans 维护"设备自报 id → 派生的通道名"。
|
||
// 设备 id 是外部输入,不能直接进通道名(见 outputch.go 的 deviceChannelName)。
|
||
devChansMu sync.Mutex
|
||
devChans map[string]string
|
||
}
|
||
|
||
func New(name string) *Plugin {
|
||
return &Plugin{
|
||
name: name,
|
||
registry: NewRegistry(),
|
||
mux: http.NewServeMux(),
|
||
}
|
||
}
|
||
|
||
func (p *Plugin) Name() string { return p.name }
|
||
|
||
func genToken() string {
|
||
buf := make([]byte, 16)
|
||
if _, err := rand.Read(buf); err != nil {
|
||
return fmt.Sprintf("tok-%d", time.Now().UnixNano())
|
||
}
|
||
return hex.EncodeToString(buf)
|
||
}
|
||
|
||
func newReqID() string {
|
||
buf := make([]byte, 8)
|
||
if _, err := rand.Read(buf); err != nil {
|
||
return fmt.Sprintf("req-%d", time.Now().UnixNano())
|
||
}
|
||
return hex.EncodeToString(buf)
|
||
}
|
||
|
||
func (p *Plugin) Start(s *sdk.PluginSDK) error {
|
||
s.SetAutoRestart(true)
|
||
p.sdk = s
|
||
|
||
// ---- 设置 ----------------
|
||
s.Settings().RegisterDef(sdk.ConfigDef{Key: "listen_addr", Default: defaultAddr, Type: "string", DisplayName: "监听地址", Description: "设备网关 HTTP/WS 监听地址(默认 127.0.0.1:9890,仅本机);填 127.0.0.1:0 让系统分配空闲端口", Category: "remotedevice"})
|
||
// ---- 反代声明(HomeAgent 自带能力)----
|
||
//
|
||
// 设备网关需要被外部访问(设备/客户端要连 WS),但它默认只监听本机
|
||
// 127.0.0.1:9890。声明后由 webui 的对外端口按 Host 子域反代出去,
|
||
// **用户不需要额外开端口或配 frp 映射**。
|
||
//
|
||
// auth=none 是**刻意的**:调用方是设备与嵌入式客户端,不可能持有浏览器
|
||
// 门户会话;本服务**自身已有接入令牌**(ws_token / X-API-Key),
|
||
// 由 requireToken 强制校验。若这里声明 homeagent(默认值),会把设备链路
|
||
// 全部挡在门户鉴权之外——那正是"认证必须可声明"的原因。
|
||
//
|
||
// websocket=true:设备注册/命令下发走 WS 长连接。
|
||
s.DeclareProxy(sdk.ProxyDecl{
|
||
Name: "gateway",
|
||
Host: "devices",
|
||
Target: "127.0.0.1:9890",
|
||
WebSocket: true,
|
||
Auth: sdk.ProxyAuthNone,
|
||
})
|
||
s.Settings().RegisterDef(sdk.ConfigDef{Key: "ws_token", Default: "", Type: "password", DisplayName: "接入 Token", Description: "设备绑定/接入时使用的令牌;留空启动时自动生成", Category: "remotedevice"})
|
||
// 注意:不注册 authorized_devices 设置项 —— 鉴权在设备端执行(客户端存储),
|
||
// 服务端不保存授权状态,避免 agent 经 config_set 工具自行授权。
|
||
|
||
p.addr = defaultAddr
|
||
if v, _ := s.Settings().Get("listen_addr"); v != nil {
|
||
if s2, ok := v.(string); ok && s2 != "" {
|
||
p.addr = s2
|
||
}
|
||
}
|
||
p.token = ""
|
||
if v, _ := s.Settings().Get("ws_token"); v != nil {
|
||
if s2, ok := v.(string); ok && s2 != "" {
|
||
p.token = s2
|
||
}
|
||
}
|
||
if p.token == "" {
|
||
p.token = genToken()
|
||
if err := s.Settings().Set("ws_token", p.token); err != nil {
|
||
log.Printf("[remotedevice] persist ws_token: %v", err)
|
||
}
|
||
}
|
||
p.registry.SetAcceptToken(func(provided string) bool {
|
||
return provided != "" && provided == p.token
|
||
})
|
||
|
||
// ---- devicectl Device(agent 工具) ----------------
|
||
p.dev = &devicectlDevice{reg: p.registry}
|
||
// screensee 视觉描述回调:截屏回传后用视觉模型描述屏幕内容
|
||
p.dev.SetSeeHandler(p.describeScreen)
|
||
if err := s.RegisterChannel("devicectl", p.dev); err != nil {
|
||
log.Printf("[remotedevice] register devicectl channel: %v", err)
|
||
}
|
||
|
||
// ---- 媒体落盘目录:<data>/device_media ----------------
|
||
// 设备回传的录像/照片等二进制聚合后写入此目录,cmd_result 返回 file 路径,
|
||
// 避免 base64 内联撑爆 LLM 上下文。目录由 logManager/运维定期清理。
|
||
if dataDir, err := s.Settings().GetCore("daemon.data_dir"); err == nil {
|
||
if dd, ok := dataDir.(string); ok && dd != "" {
|
||
p.registry.SetMediaDir(filepath.Join(dd, "device_media"))
|
||
}
|
||
}
|
||
|
||
// ---- 设备通道随在线状态生灭(见 outputch.go 的 wireDeviceChannels)----
|
||
p.wireDeviceChannels()
|
||
|
||
// ---- 设备主动上报事件 → agent 注入 ----------------
|
||
// 摄像头发现异常/传感器报警等场景:设备经 WS op=event 上报,
|
||
// 插件将其格式化为文本经 SDK InjectText 异步注入 agent(source=device/{id}),
|
||
// 同时发 EventBus 供 WebUI 展示。
|
||
//
|
||
// **注意**:agent 的输出**不会**被自动转回设备 —— 主动转发只有 webui 与 cli 两个
|
||
// 交互界面(它们把最终回复渲染成对话气泡是本职)。设备要走
|
||
// `output_send__device-<id>`(agent 主动调用),这才与"输出是 agent 的主动调用"一致。
|
||
// 节流:同设备同类型事件 10s 内去重,防传感器风暴。
|
||
lastEventAt := map[string]time.Time{}
|
||
var eventMu sync.Mutex
|
||
p.registry.SetEventHandler(func(deviceID string, msg map[string]interface{}) {
|
||
evtType, _ := msg["type"].(string)
|
||
if evtType == "" {
|
||
evtType = "unknown"
|
||
}
|
||
key := deviceID + "|" + evtType
|
||
eventMu.Lock()
|
||
if last, ok := lastEventAt[key]; ok && time.Since(last) < 10*time.Second {
|
||
eventMu.Unlock()
|
||
log.Printf("[remotedevice] event throttled: %s from %s", evtType, deviceID)
|
||
return
|
||
}
|
||
lastEventAt[key] = time.Now()
|
||
eventMu.Unlock()
|
||
|
||
// 组装人类可读的事件文本(agent 可直接理解)
|
||
detail, _ := msg["detail"].(string)
|
||
if detail == "" {
|
||
if d, ok := msg["payload"].(map[string]interface{}); ok {
|
||
b, _ := json.Marshal(d)
|
||
detail = string(b)
|
||
}
|
||
}
|
||
text := fmt.Sprintf("【设备事件上报】设备 %s 触发事件 %s", deviceID, evtType)
|
||
if detail != "" {
|
||
text += ":" + detail
|
||
}
|
||
text += "。请关注此事件并按需处理(如通知用户、调用相关工具核实)。"
|
||
|
||
log.Printf("[remotedevice] event from %s: %s", deviceID, evtType)
|
||
if p.sdk != nil {
|
||
// 设备通道 device-<id> 是动态的(分隔符用 - 而非 /,见 deviceChannelName 的说明:
|
||
// 通道名会进 LLM 函数名,必须满足 ^[a-zA-Z0-9_-]{1,64}$)。
|
||
// 首次上报时**懒登记** inputch(Register 幂等),父 agent 才能把它划给驻留子。
|
||
devCh := p.deviceChannelName(deviceID)
|
||
_ = p.sdk.RegisterInputChannel(devCh, sdk.ChannelDef{})
|
||
// 异步注入:不阻塞 WS 读循环;回复路由回 device/{id} 输出通道
|
||
p.sdk.InjectInput(devCh, devCh, "text", map[string]interface{}{"content": text})
|
||
}
|
||
})
|
||
|
||
// ---- REST 管理面 + WS 设备通道 ----------------
|
||
p.registerRoutes()
|
||
|
||
// 显式 net.Listen + Serve,而非 ListenAndServe:
|
||
//
|
||
// 1. 配 `127.0.0.1:0` 时只有 net.Listener 知道真实端口,ListenAndServe 拿不到。
|
||
// 这不只是测试便利——它是 `:0` 语义能工作的前提(多实例/沙箱需要)。
|
||
// 2. 监听失败必须**可见**:此前 ListenAndServe 在后台 goroutine 里报错,
|
||
// 端口被占时只打一行日志、Start 仍返回 nil(插件表面「已加载」而网关根本没跑)。
|
||
// 现在在 Start 里同步 Listen,把错误交给调用方。
|
||
ln, err := net.Listen("tcp", p.addr)
|
||
if err != nil {
|
||
return fmt.Errorf("remotedevice: 监听 %s 失败: %w", p.addr, err)
|
||
}
|
||
// 用**实际绑定**地址回写,使日志与诊断面显示真实端口(配 :0 时尤其重要)。
|
||
p.addr = ln.Addr().String()
|
||
|
||
p.server = &http.Server{Handler: p.mux}
|
||
go func() {
|
||
log.Printf("[remotedevice] device gateway listening on %s", p.addr)
|
||
if err := p.server.Serve(ln); err != nil && err != http.ErrServerClosed {
|
||
log.Printf("[remotedevice] server error: %v", err)
|
||
}
|
||
}()
|
||
return nil
|
||
}
|
||
|
||
func (p *Plugin) registerRoutes() {
|
||
// 设备通道(WS)
|
||
p.mux.HandleFunc("/api/v1/device/ws", p.registry.ServeWS)
|
||
// REST 管理面(全部需 token)
|
||
// 注意:/api/v1/device/auth 已移除 —— 授权由设备端控制,服务端不提供授权接口。
|
||
p.mux.HandleFunc("/api/v1/device", p.requireToken(p.handleDeviceList))
|
||
p.mux.HandleFunc("/api/v1/device/online", p.requireToken(p.handleDeviceOnline))
|
||
p.mux.HandleFunc("/api/v1/device/", p.requireToken(p.handleDeviceByID))
|
||
p.mux.HandleFunc("/api/v1/device/push", p.requireToken(p.handleDevicePush))
|
||
}
|
||
|
||
// requireToken 校验 REST 请求的接入令牌(X-API-Key header 或 ?token=)。
|
||
func (p *Plugin) requireToken(next http.HandlerFunc) http.HandlerFunc {
|
||
return func(w http.ResponseWriter, r *http.Request) {
|
||
k := r.Header.Get("X-API-Key")
|
||
if k == "" {
|
||
k = r.URL.Query().Get("token")
|
||
}
|
||
if k == "" || k != p.token {
|
||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||
return
|
||
}
|
||
next(w, r)
|
||
}
|
||
}
|
||
|
||
func writeJSON(w http.ResponseWriter, status int, v interface{}) {
|
||
w.Header().Set("Content-Type", "application/json")
|
||
w.WriteHeader(status)
|
||
_ = json.NewEncoder(w).Encode(v)
|
||
}
|
||
|
||
func (p *Plugin) handleDeviceList(w http.ResponseWriter, r *http.Request) {
|
||
if r.Method != http.MethodGet {
|
||
http.NotFound(w, r)
|
||
return
|
||
}
|
||
writeJSON(w, http.StatusOK, map[string]interface{}{"devices": p.registry.List()})
|
||
}
|
||
|
||
func (p *Plugin) handleDeviceOnline(w http.ResponseWriter, r *http.Request) {
|
||
if r.Method != http.MethodGet {
|
||
http.NotFound(w, r)
|
||
return
|
||
}
|
||
writeJSON(w, http.StatusOK, map[string]interface{}{"devices": p.registry.OnlineList()})
|
||
}
|
||
|
||
func (p *Plugin) handleDeviceByID(w http.ResponseWriter, r *http.Request) {
|
||
id := strings.TrimPrefix(r.URL.Path, "/api/v1/device/")
|
||
if id == "" || strings.Contains(id, "/") {
|
||
http.NotFound(w, r)
|
||
return
|
||
}
|
||
if r.Method == http.MethodGet {
|
||
m, ok := p.registry.Get(id)
|
||
if !ok {
|
||
writeJSON(w, http.StatusNotFound, map[string]interface{}{"error": "device not found"})
|
||
return
|
||
}
|
||
writeJSON(w, http.StatusOK, m)
|
||
return
|
||
}
|
||
http.NotFound(w, r)
|
||
}
|
||
|
||
func (p *Plugin) handleDevicePush(w http.ResponseWriter, r *http.Request) {
|
||
if r.Method != http.MethodPost {
|
||
http.NotFound(w, r)
|
||
return
|
||
}
|
||
var req struct {
|
||
DeviceID string `json:"device_id"`
|
||
Payload map[string]interface{} `json:"payload"`
|
||
}
|
||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||
writeJSON(w, http.StatusBadRequest, map[string]interface{}{"error": err.Error()})
|
||
return
|
||
}
|
||
if req.DeviceID == "" {
|
||
writeJSON(w, http.StatusBadRequest, map[string]interface{}{"error": "device_id required"})
|
||
return
|
||
}
|
||
if err := p.registry.PushJSON(req.DeviceID, req.Payload); err != nil {
|
||
writeJSON(w, http.StatusNotFound, map[string]interface{}{"error": err.Error()})
|
||
return
|
||
}
|
||
writeJSON(w, http.StatusOK, map[string]interface{}{"status": "ok"})
|
||
}
|
||
|
||
// describeScreen 用视觉模型描述设备屏幕截图(screensee 回调)。
|
||
// provider 为空时使用默认 LLM 源;模型不支持视觉时返回友好错误。
|
||
func (p *Plugin) describeScreen(dataURL string, provider string) string {
|
||
if p.sdk == nil || p.sdk.LLM() == nil {
|
||
return "LLM 不可用,无法描述屏幕内容"
|
||
}
|
||
llm := p.sdk.LLM()
|
||
req := &sdk.LLMCompletionRequest{
|
||
MaxTokens: 2048,
|
||
Messages: []sdk.LLMMessage{{
|
||
Role: "user",
|
||
Blocks: []sdk.LLMContentBlock{
|
||
{Type: "text", Text: "这是用户设备的屏幕截图。请详细描述屏幕上显示的内容:正在运行的窗口/应用、可见的文字内容、界面状态等。如果是代码编辑器或终端,尽量转述关键文字信息。"},
|
||
{Type: "image_url", ImageURL: dataURL},
|
||
},
|
||
}},
|
||
}
|
||
// 指定源:临时切换(低频操作,用完恢复原源)
|
||
if provider != "" {
|
||
prev := llm.CurrentSource()
|
||
if err := llm.SetSource(provider); err != nil {
|
||
log.Printf("[remotedevice] screensee set source %s: %v", provider, err)
|
||
} else if prev != "" {
|
||
defer func() { _ = llm.SetSource(prev) }()
|
||
}
|
||
}
|
||
ctx, cancel := context.WithTimeout(context.Background(), 120*time.Second)
|
||
defer cancel()
|
||
resp, err := llm.Chat(ctx, req)
|
||
if err != nil {
|
||
return fmt.Sprintf("屏幕截图视觉描述失败: %v(当前模型可能不支持图像输入)", err)
|
||
}
|
||
return resp.Content
|
||
}
|
||
|
||
func (p *Plugin) Stop() error {
|
||
// 注销全部设备通道:插件卸载/重载后这些通道不再有实现,
|
||
// 留着会让 output_list_channels 骗模型。
|
||
if p.sdk != nil {
|
||
for _, m := range p.registry.List() {
|
||
p.dropDeviceOutputChannel(m.DeviceID)
|
||
}
|
||
}
|
||
if p.server != nil {
|
||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||
defer cancel()
|
||
return p.server.Shutdown(ctx)
|
||
}
|
||
return nil
|
||
}
|