From d17c18665cddfc9de51f7a0cb5ea75f536b74edb Mon Sep 17 00:00:00 2001 From: JianFeeeee Date: Sun, 13 Sep 2026 13:07:24 +0800 Subject: [PATCH] =?UTF-8?q?fix(remotedevice):=20=E8=AE=BE=E5=A4=87?= =?UTF-8?q?=E9=80=9A=E9=81=93=E5=90=8D=E6=94=B9=E7=94=A8=20`-`=20=E5=88=86?= =?UTF-8?q?=E9=9A=94=E5=B9=B6=E6=B4=BE=E7=94=9F=E5=90=88=E8=A7=84=E5=90=8D?= =?UTF-8?q?=EF=BC=88v1.3.0=20=E9=83=A8=E7=BD=B2=E5=90=8E=20agent=20?= =?UTF-8?q?=E5=AE=8C=E5=85=A8=E4=B8=8D=E5=BA=94=E7=AD=94=E7=9A=84=E6=A0=B9?= =?UTF-8?q?=E5=9B=A0=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## 事故 v1.3.0 部署到生产后,**整个 agent 不应答**:任何对话都返回 `all 3 providers failed, last error: api error 403: model "claude-opus-5" is not allowed for this key`。 回滚到 1.2.2 立即恢复(部署前 403=0/成功对话=10,部署后 403=5/成功对话=0)。 ## 根因(网关日志给出的原文) ``` tier 3 gozen/deepseek-v4.1-flash: api error 400: [invalid_request_error] Invalid 'tools[299].function.name': string does not match pattern '^[a-zA... ``` 设备的每设备输出通道名叫 `device/`,内核按 `output_send__<通道名>` 生成工具 ⇒ `output_send__device/` 里的 `/` 违反上游函数名规范 `^[a-zA-Z0-9_-]{1,64}$`。 上游不是"拒掉这一个工具",而是**整条请求 400** ⇒ 网关 auto tier 全链条失败 (400/429/503 混在一起)⇒ 内核只能报"所有 provider 都失败"。 两台真实设备(waiter-fnnas / waiter-mainnas)一上线就登记了这种通道,于是必然触发。 ## 修法(改插件,不改内核) 初版我在内核里加了"通道名净化 + 反向解析"层。用户否掉了这个方向,理由对: **通道名是插件自己的声明,不合契约就该改插件**,不该让内核替插件擦屁股。 内核侧改动已全部回退(HEAD 干净)。 插件侧两处: 1. 分隔符 `device/` → `device-`(源码与来源标签统一,不留两套名字)。 2. 设备 id 是**外部输入**(设备自己声明),可能含空格/非 ASCII/超长 ⇒ `deviceChannelName()` 把它派生为**合规且唯一**的通道名: 保留 `[A-Za-z0-9_-]`、其它折成 `-`、主体截断到 32 字符(预算 64 = 13+7+32+7+…)、 发生截断或撞名时追加 id 的 6 位短哈希。同一 id 恒定同名;真名仍用于路由与日志。 核心契约写进了插件注释与 SDK 文档(见 SDK 仓同批提交):名字若来自外部输入, **在插件侧派生合规名**,内核不会替你净化。 ## 验证 - 新增 `TestDeviceChannelNameIsLLMFunctionNameSafe`:恶意 id(空格/符号/非 ASCII/超长/ 会折成同名的两个 id)都必须派生出**合法且互不重复**的通道名与工具名。 反向验证:把分隔符改回 `/` 即 FAIL。 - 生产两台设备派生结果:`device-waiter-fnnas`、`device-waiter-mainnas` ⇒工具名 `output_send__device-waiter-fnnas`(37 字符,合规)。 - 全量 `go test ./...` = 37 包 ok / 0 FAIL;`-race`(remotedevice + core)无 DATA RACE。 --- internal/plugins/remotedevice/outputch.go | 85 ++++++++++++++++--- .../plugins/remotedevice/outputch_test.go | 32 ++++++- internal/plugins/remotedevice/plugin.go | 14 ++- internal/plugins/remotedevice/registry.go | 2 +- 4 files changed, 116 insertions(+), 17 deletions(-) diff --git a/internal/plugins/remotedevice/outputch.go b/internal/plugins/remotedevice/outputch.go index de1ea0a..a9c82bb 100644 --- a/internal/plugins/remotedevice/outputch.go +++ b/internal/plugins/remotedevice/outputch.go @@ -1,9 +1,9 @@ package remotedevice -// 设备输出通道:把"agent 主动发给设备"做成**每设备一个输出通道** `device/`。 +// 设备输出通道:把"agent 主动发给设备"做成**每设备一个输出通道** `device-`。 // // 为什么是输出通道而不是再加一批工具: -// - **寻址**:`output_send__device/` 直接指名道姓;模型看 `output_list_channels` +// - **寻址**:`output_send__device-` 直接指名道姓;模型看 `output_list_channels` // 就知道当前有哪些设备在线,不必先 `devicedetect` 再往参数里塞 device_id。 // - **能力**:caps 由设备声明的 caps 映射,**内核**在发送前就按 caps 拦 // (把图片发给只支持文本的音箱会被拒,而不是等设备侧报错)。 @@ -15,7 +15,9 @@ package remotedevice // 它们的返回值(图像/命令输出/状态)必须进模型上下文,做成通道会丢掉这个语义。 import ( + "crypto/sha1" "encoding/base64" + "encoding/hex" "encoding/json" "fmt" "log" @@ -76,14 +78,75 @@ func deviceOutputCaps(caps []string, kind string) agentIO.OutputCapability { return out } -// deviceChannelName 是设备输出(也是输入)通道名:`device/`。 +// deviceChannelName 由**设备自报的 id** 派生一个合规且唯一的通道名:`device-<派生值>`。 // // 入站与出站**同名**:两者指的是同一台设备,分成两个名字只会让模型与授权表更难对。 -func deviceChannelName(id string) string { return "device/" + id } +// +// 为什么不能直接用 id:通道名会被内核拼进 LLM 的**函数名**(`output_send__<通道名>`), +// 上游规范是 `^[a-zA-Z0-9_-]{1,64}$`;而设备 id 是**外部输入**(设备自己声明), +// 可能含空格/非 ASCII/超长。违规的后果不是"这个工具不能用",而是**整条请求被 400 拒绝** —— +// 实测把生产打挂:`Invalid 'tools[299].function.name'`,网关 auto tier 全链条失败, +// 内核只能报"所有 provider 都失败",表现成"整个 agent 不说话了"。 +// +// 派生规则(确定性,同一 id 永远同名): +// 1. 保留 [A-Za-z0-9_-],其它字符折成 '-';折叠后为空则用 "dev" +// 2. 截断到 maxDeviceChannelSuffix 字符(给 "device-" 与短哈希留余量) +// 3. 若发生截断,或该名字已被**另一个** id 占用,则追加 id 的 6 位短哈希 +// +// 设备 id 本身仍用于路由与日志(真名不丢),通道名只是它派生的标识符。 +func (p *Plugin) deviceChannelName(id string) string { + p.devChansMu.Lock() + defer p.devChansMu.Unlock() + if p.devChans == nil { + p.devChans = make(map[string]string) + } + if name, ok := p.devChans[id]; ok { + return name + } + var b strings.Builder + for _, r := range id { + switch { + case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9', r == '_', r == '-': + b.WriteRune(r) + default: + b.WriteByte('-') + } + } + base := b.String() + if base == "" { + base = "dev" + } + truncated := false + if len(base) > maxDeviceChannelSuffix { + base = base[:maxDeviceChannelSuffix] + truncated = true + } + name := "device-" + base + // 撞名检查:不同 id 折出同一个名字时必须可区分 + for otherID, otherName := range p.devChans { + if otherName == name && otherID != id { + truncated = true + break + } + } + if truncated { + sum := sha1.Sum([]byte(id)) + name += "-" + hex.EncodeToString(sum[:3]) + } + p.devChans[id] = name + return name +} + +const ( + // maxDeviceChannelSuffix 是通道名主体的长度上限。 + // 预算:上游函数名上限 64 = "output_send__"(13) + "device-"(7) + 主体 + "-"+短哈希(7) + // ⇒ 主体最多 37;取 32 留余量(改名/前缀变动不会立刻越界)。 + maxDeviceChannelSuffix = 32 +) // wireDeviceChannels 把"设备上下线"接到通道的登记/注销上。 // -// 一台设备 = 一对**同名**通道 `device/`:入站(设备上报 → agent)与出站 +// 一台设备 = 一对**同名**通道 `device-`:入站(设备上报 → agent)与出站 // (agent → 设备)。用**同步回调**而不是 ChangeChan(后者是 select+default, // 缓冲满会丢事件;丢一次就留下死通道或漏注册)。 // @@ -92,14 +155,14 @@ func deviceChannelName(id string) string { return "device/" + id } func (p *Plugin) wireDeviceChannels() { p.registry.SetPresenceHandler( func(meta DeviceMeta) { - _ = p.sdk.RegisterInputChannel(deviceChannelName(meta.DeviceID), sdk.ChannelDef{}) + _ = p.sdk.RegisterInputChannel(p.deviceChannelName(meta.DeviceID), sdk.ChannelDef{}) p.ensureDeviceOutputChannel(meta.DeviceID) }, func(id string) { p.dropDeviceOutputChannel(id) }, ) } -// ensureDeviceOutputChannel 给在线设备注册输出通道 device/(幂等)。 +// ensureDeviceOutputChannel 给在线设备注册输出通道 device-(幂等)。 func (p *Plugin) ensureDeviceOutputChannel(id string) { if p.sdk == nil || id == "" { return @@ -108,7 +171,7 @@ func (p *Plugin) ensureDeviceOutputChannel(id string) { if !ok || !meta.Online { return } - ch := deviceChannelName(id) + ch := p.deviceChannelName(id) caps := deviceOutputCaps(meta.Caps, meta.Kind) desc := fmt.Sprintf("远程设备 %s(%s):agent 主动向该设备发送内容;能力位 %s", id, fallback(meta.Name, meta.Kind), agentIO.OutputCapability(caps).String()) @@ -130,7 +193,7 @@ func (p *Plugin) dropDeviceOutputChannel(id string) { if p.sdk == nil || id == "" { return } - ch := deviceChannelName(id) + ch := p.deviceChannelName(id) if err := p.sdk.UnregisterOutputChannel(ch); err != nil { p.logf("unregister output channel %s: %v", ch, err) return @@ -247,9 +310,9 @@ func (d *devicectlDevice) output(args map[string]interface{}) (interface{}, erro ids = append(ids, m.DeviceID) } if len(ids) == 0 { - return nil, fmt.Errorf("devicectl 需要 meta.device_id 才能投递;当前没有在线设备(device_list_channels 可看每台设备的 device/ 通道)") + return nil, fmt.Errorf("devicectl 需要 meta.device_id 才能投递;当前没有在线设备(device_list_channels 可看每台设备的 device- 通道)") } - return nil, fmt.Errorf("devicectl 需要 meta.device_id(或直接用通道 device/);当前在线设备: %s", strings.Join(ids, ", ")) + return nil, fmt.Errorf("devicectl 需要 meta.device_id(或直接用通道 device-);当前在线设备: %s", strings.Join(ids, ", ")) } return pushToDevice(d.reg, deviceID, args) } diff --git a/internal/plugins/remotedevice/outputch_test.go b/internal/plugins/remotedevice/outputch_test.go index 5a74ca8..fac64e1 100644 --- a/internal/plugins/remotedevice/outputch_test.go +++ b/internal/plugins/remotedevice/outputch_test.go @@ -9,6 +9,8 @@ import ( "encoding/json" "net/http" "net/http/httptest" + "regexp" + "strings" "sync" "testing" "time" @@ -130,7 +132,7 @@ func TestDeviceChannelLifecycleAndPush(t *testing.T) { cli.sendText([]byte(`{"op":"hello","device":{"device_id":"spk-1","name":"音箱","kind":"speaker","caps":["speaker"]}}`)) cli.readHelloAckAndBind(t, token) - ch := deviceChannelName("spk-1") + ch := p.deviceChannelName("spk-1") deadline := time.Now().Add(3 * time.Second) caps, ok := rec.caps(ch) for !ok && time.Now().Before(deadline) { @@ -255,3 +257,31 @@ func TestDevicectlAggregateOutputAddressing(t *testing.T) { t.Fatal("不存在的设备应报错") } } + +// 通道名合规性:设备通道名会被内核拼进 LLM **函数名**(output_send__<通道名>), +// 而上游函数名规范是 ^[a-zA-Z0-9_-]{1,64}$ —— 违规会让**整条请求**被 400 拒绝 +// (实测把生产打挂:device/ 里的 `/` 触发 Invalid 'tools[299].function.name', +// 网关 auto tier 全链条失败,整个 agent 不说话了)。 +// +// 通道名是**插件自己的声明**,所以这条判据钉在插件侧。 +func TestDeviceChannelNameIsLLMFunctionNameSafe(t *testing.T) { + re := regexp.MustCompile(`^[a-zA-Z0-9_-]{1,64}$`) + // 含**恶意/异常** id:空格、符号、非 ASCII、超长、以及会折成同一个名字的两个 id + ids := []string{"waiter-fnnas", "1", "a b!c", "中文设备", strings.Repeat("x", 120), "a b", "a-b"} + p := &Plugin{} + seen := map[string]string{} + for _, id := range ids { + ch := p.deviceChannelName(id) + if prev, dup := seen[ch]; dup { + t.Errorf("不同设备 id(%q 与 %q)派生出同一个通道名 %q", prev, id, ch) + } + seen[ch] = id + if !re.MatchString(ch) { + t.Errorf("设备通道名 %q 违反上游函数名规范 %s", ch, re) + } + toolName := "output_send__" + ch + if !re.MatchString(toolName) { + t.Errorf("派生出的工具名 %q 违反上游函数名规范 %s", toolName, re) + } + } +} diff --git a/internal/plugins/remotedevice/plugin.go b/internal/plugins/remotedevice/plugin.go index b3b2da0..ec7a240 100644 --- a/internal/plugins/remotedevice/plugin.go +++ b/internal/plugins/remotedevice/plugin.go @@ -37,6 +37,11 @@ type Plugin struct { 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 { @@ -124,7 +129,7 @@ func (p *Plugin) Start(s *sdk.PluginSDK) error { // // **注意**:agent 的输出**不会**被自动转回设备 —— 主动转发只有 webui 与 cli 两个 // 交互界面(它们把最终回复渲染成对话气泡是本职)。设备要走 - // `output_send__device/`(agent 主动调用),这才与"输出是 agent 的主动调用"一致。 + // `output_send__device-`(agent 主动调用),这才与"输出是 agent 的主动调用"一致。 // 节流:同设备同类型事件 10s 内去重,防传感器风暴。 lastEventAt := map[string]time.Time{} var eventMu sync.Mutex @@ -159,9 +164,10 @@ func (p *Plugin) Start(s *sdk.PluginSDK) error { log.Printf("[remotedevice] event from %s: %s", deviceID, evtType) if p.sdk != nil { - // 设备通道 device/ 是动态的:设备首次上报时**懒登记** inputch - // (Register 幂等),父 agent 才能把它划给驻留子。 - devCh := "device/" + deviceID + // 设备通道 device- 是动态的(分隔符用 - 而非 /,见 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}) diff --git a/internal/plugins/remotedevice/registry.go b/internal/plugins/remotedevice/registry.go index 54b3965..0bb3c8c 100644 --- a/internal/plugins/remotedevice/registry.go +++ b/internal/plugins/remotedevice/registry.go @@ -287,7 +287,7 @@ func (r *Registry) register(meta DeviceMeta) { r.devices[meta.DeviceID] = &meta onOnline := r.onOnline r.mu.Unlock() - // 先回调(可能注册 device/ 输出通道),再发变更通知。 + // 先回调(可能注册 device- 输出通道),再发变更通知。 if onOnline != nil { onOnline(meta) }