mirror of
https://gitcode.com/JianFeeeee/HomeAgent.git
synced 2026-09-22 09:58:06 +00:00
Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 1d46c6c0f6 | |||
| 4707b05498 | |||
| f5df904d02 | |||
| 8537577123 |
@ -325,7 +325,7 @@ func New(cfg AgentConfig) *Agent {
|
||||
}
|
||||
}
|
||||
|
||||
return &Agent{
|
||||
a := &Agent{
|
||||
id: cfg.ID,
|
||||
startTime: time.Now(),
|
||||
provider: cfg.Provider,
|
||||
@ -376,6 +376,14 @@ func New(cfg AgentConfig) *Agent {
|
||||
noMergeMarkers: make(map[string]int),
|
||||
lastInput: make(map[string]time.Time),
|
||||
}
|
||||
|
||||
// 输入路由:inputch 是可分配资源,划给某个 agent 后输入**只**流向那个 agent
|
||||
// (设计 §4.1「路由发生在进内核之前」)。io 层不认识 agent,所以在这里把路由器
|
||||
// 注入进去:插件注入输入时先问它,被别的 agent 接管就不再进本内核队列。
|
||||
if a.io != nil {
|
||||
a.io.SetInputRouter(a.routeInputByOwner)
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
// SetSkillIndexProvider 注入技能索引提供者(skillmgr 插件加载后由 main 接线)。
|
||||
|
||||
44
internal/agent/core/inputroute.go
Normal file
44
internal/agent/core/inputroute.go
Normal file
@ -0,0 +1,44 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
agentIO "gitcode.com/JianFeeeee/HomeAgent/internal/agent/io"
|
||||
)
|
||||
|
||||
// routeInputByOwner 实现**输入路由**:inputch 是最基本的输入路由单位,
|
||||
// 划给某个 agent 之后,该通道的输入**只流向那个 agent**,本内核看不到它
|
||||
// (docs/zh/resident-subagent-design.md §4.1:「路由发生在进内核之前」)。
|
||||
//
|
||||
// 为什么必须在进内核之前做:插件注入输入的收口是**父**的 IOManager
|
||||
// (`cmd/homed` 里 pluginReg 拿到的就是它),而父的内核是该 io 唯一的消费者。
|
||||
// 如果不按归属路由,登记表里的 Owner 就只是个标签 —— 现场表现正是如此:
|
||||
// 子挂着 `inputch=[timer]`,timer 的输入却打在父身上,子的轮次永远是 0。
|
||||
//
|
||||
// 返回 true = 本次注入已被"持有该 inputch 的 agent"接管,本内核不再处理。
|
||||
//
|
||||
// 已知边界:路由只在本 agent 的**直接**驻留子里找。若孙辈的 inputch 由子划拨,
|
||||
// 而插件注入打在根 io 上,根解析不到那个 owner ⇒ 兜底给根处理(有日志)。
|
||||
// 这一层要等"孙辈 + 根可见的 agent 表"再收口,此处不静默丢输入。
|
||||
func (a *Agent) routeInputByOwner(evt *agentIO.InputEvent, isInterrupt bool) bool {
|
||||
if evt == nil || evt.OutputChannel == "" || a.io == nil {
|
||||
return false
|
||||
}
|
||||
entry, ok := a.io.LookupInputChannel(evt.OutputChannel)
|
||||
if !ok || entry.Owner == "" || entry.Owner == string(a.id) {
|
||||
return false // 未分配 / 归自己 ⇒ 本内核处理
|
||||
}
|
||||
|
||||
a.residentMu.Lock()
|
||||
rc := a.residents[entry.Owner]
|
||||
a.residentMu.Unlock()
|
||||
if rc == nil || rc.agent == nil || rc.agent.io == nil {
|
||||
// 归属到一个不存在(或已销毁、登记表尚未归还)的 agent:
|
||||
// **不吞输入** —— 由本内核兜底处理并留痕。吞掉一条输入比多处理一条更糟:
|
||||
// 用户会看到"消息发出去了却没人理",而日志里什么都没有。
|
||||
log.Printf("[route] inputch %s 归属 %s 无对应 agent,输入由 %s 兜底", evt.OutputChannel, entry.Owner, a.id)
|
||||
return false
|
||||
}
|
||||
rc.agent.io.DeliverRouted(evt, isInterrupt)
|
||||
return true
|
||||
}
|
||||
80
internal/agent/core/inputroute_test.go
Normal file
80
internal/agent/core/inputroute_test.go
Normal file
@ -0,0 +1,80 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
agentIO "gitcode.com/JianFeeeee/HomeAgent/internal/agent/io"
|
||||
)
|
||||
|
||||
// 输入路由是**独占**的:inputch 划给子之后,该通道的输入只流向子,父不再收到。
|
||||
//
|
||||
// 现场缺陷(用户线上联调实录):子挂着 inputch=[timer],timer 的输入却打在父身上
|
||||
// (日志 `[agent] interrupt from timer/timer`),子的轮次永远是 0 —— 因为
|
||||
// `Assign` 只把 Owner 写进登记表,注入路径根本没有按归属路由。
|
||||
func TestResident_InputchRoutingIsExclusive(t *testing.T) {
|
||||
parent, _, dir := newRootForResidents(t)
|
||||
reg := parent.io.ChannelRegistry()
|
||||
if err := reg.Register(agentIO.InputChannel{Name: "sub/in", Plugin: "sub"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
spawnTestResident(t, parent, dir, "r-route", "sub/in")
|
||||
child := parent.residents["r-route"].agent
|
||||
|
||||
before := parent.DumpScheduler().Stats.Enqueued
|
||||
// 插件往"已划给子"的 inputch 投输入
|
||||
parent.io.InjectTextTo("plugin-sub", "sub/in", "去查一下这个")
|
||||
|
||||
waitFor(t, "子处理了划给它的输入", func() bool {
|
||||
if child.DumpScheduler().Stats.Executed > 0 {
|
||||
return true
|
||||
}
|
||||
return parent.residents["r-route"].info().TableSize > 0
|
||||
})
|
||||
if got := parent.DumpScheduler().Stats.Enqueued; got != before {
|
||||
t.Fatalf("划给子的 inputch,父不应再入队(before=%d after=%d)", before, got)
|
||||
}
|
||||
}
|
||||
|
||||
// 归属到一个不存在(或已销毁)的 agent 时**不吞输入**:父兜底处理。
|
||||
// 吞掉一条输入比多处理一条更糟 —— 用户会看到"消息发出去了却没人理",日志里什么都没有。
|
||||
func TestResident_InputchRoutingFallsBackWhenOwnerMissing(t *testing.T) {
|
||||
parent, _, dir := newRootForResidents(t)
|
||||
reg := parent.io.ChannelRegistry()
|
||||
if err := reg.Register(agentIO.InputChannel{Name: "ghost/in", Plugin: "ghost"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// 故意划给一个不存在的 agent id
|
||||
if err := reg.Assign("ghost/in", "no-such-agent", 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = dir
|
||||
|
||||
before := parent.DumpScheduler().Stats.Enqueued
|
||||
parent.io.InjectTextTo("plugin-ghost", "ghost/in", "兜底测试")
|
||||
waitFor(t, "父兜底处理了无人认领的输入", func() bool {
|
||||
return parent.DumpScheduler().Stats.Enqueued > before
|
||||
})
|
||||
}
|
||||
|
||||
// 未划拨的 inputch(Owner 为空)仍然由父处理 —— 路由不能把默认路径也改掉。
|
||||
func TestResident_UnassignedInputchStaysWithParent(t *testing.T) {
|
||||
parent, _, dir := newRootForResidents(t)
|
||||
reg := parent.io.ChannelRegistry()
|
||||
if err := reg.Register(agentIO.InputChannel{Name: "own/in", Plugin: "own"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// 造一个子在跑,确保路由逻辑是"有子存在"的情形
|
||||
spawnTestResident(t, parent, dir, "r-other", "own/in")
|
||||
_ = filepath.Join(dir, "residents")
|
||||
|
||||
// 把通道退还给父(未分配)
|
||||
if err := reg.Assign("own/in", "", 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before := parent.DumpScheduler().Stats.Enqueued
|
||||
parent.io.InjectTextTo("plugin-own", "own/in", "还是我的")
|
||||
waitFor(t, "未分配的 inputch 仍由父处理", func() bool {
|
||||
return parent.DumpScheduler().Stats.Enqueued > before
|
||||
})
|
||||
}
|
||||
@ -132,11 +132,17 @@ func (a *Agent) SpawnResident(opts ResidentOptions) (ResidentInfo, error) {
|
||||
}
|
||||
}
|
||||
|
||||
// ③ 子的 io:**独立**的 IOManager(自己的输入通道入口),但共享通道登记表。
|
||||
// ③ 子的 io:**独立**的 IOManager(自己的输入通道入口),但共享通道登记表,
|
||||
// 并把父的 io 挂成"上级"——**输出通道(io 里的 Device)由插件登记在父的 io 上**,
|
||||
// 子若不继承这张视图,`output_send__<通道>` 一律被判"通道不存在或不可用"、
|
||||
// `output_list_channels` 为空、连 `output_send__*` 工具都不会生成
|
||||
// (现场联调:父侧通道装载完整、子侧 childIO 空壳)。
|
||||
// 回退是实时的(设备随资源生灭),授权仍由 opts.AllowedOutputs 白名单把关。
|
||||
childIO := agentIO.NewIOManager()
|
||||
if reg := a.io.ChannelRegistry(); reg != nil {
|
||||
childIO.SetChannelRegistry(reg)
|
||||
}
|
||||
childIO.SetParentIO(a.io)
|
||||
|
||||
parentID := string(a.id)
|
||||
child := New(AgentConfig{
|
||||
|
||||
145
internal/agent/core/resident_output_test.go
Normal file
145
internal/agent/core/resident_output_test.go
Normal file
@ -0,0 +1,145 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
agentAPI "gitcode.com/JianFeeeee/HomeAgent/internal/agent/api"
|
||||
agentIO "gitcode.com/JianFeeeee/HomeAgent/internal/agent/io"
|
||||
)
|
||||
|
||||
// outputTestDevice 是最小的输出通道替身(io 里输出通道就是 Device)。
|
||||
type outputTestDevice struct {
|
||||
name string
|
||||
sent []map[string]interface{}
|
||||
}
|
||||
|
||||
func (d *outputTestDevice) Name() string { return d.name }
|
||||
func (d *outputTestDevice) Type() agentIO.DeviceType { return agentIO.DeviceOutput }
|
||||
func (d *outputTestDevice) Description() string { return "测试输出通道" }
|
||||
func (d *outputTestDevice) Tools() []agentIO.ToolDef { return nil }
|
||||
func (d *outputTestDevice) Start() error { return nil }
|
||||
func (d *outputTestDevice) Stop() error { return nil }
|
||||
func (d *outputTestDevice) OutputCapabilities() agentIO.OutputCapability { return agentIO.CapText }
|
||||
func (d *outputTestDevice) ChannelDef() agentIO.ChannelDef { return agentIO.ChannelDef{} }
|
||||
func (d *outputTestDevice) Execute(tool string, args map[string]interface{}) (interface{}, error) {
|
||||
d.sent = append(d.sent, map[string]interface{}{"tool": tool, "args": args})
|
||||
return map[string]interface{}{"status": "sent"}, nil
|
||||
}
|
||||
|
||||
func outputSendTool(name, payload string) agentAPI.ToolCall {
|
||||
return agentAPI.ToolCall{
|
||||
Name: "output_send__" + name,
|
||||
Arguments: map[string]interface{}{"payload": payload, "type": "text"},
|
||||
}
|
||||
}
|
||||
|
||||
// 驻留子必须能看见并使用**父**登记的输出通道。
|
||||
//
|
||||
// 现场缺陷(联调实录):父侧通道装载完整、子侧 childIO 空壳 ——
|
||||
// 子调 output_send__X 被 `GetChannelCapabilities` 判 0 ⇒
|
||||
// 「通道 [X] 不存在或不可用。可用输出工具列表见 output_list_channels」,
|
||||
// 而 output_list_channels 也是空的。根因是子的 io 是新建的、设备表为空,
|
||||
// 而输出通道(io 的 Device)由插件登记在父的 io 上。
|
||||
func TestResident_InheritsParentOutputChannels(t *testing.T) {
|
||||
parent, _, dir := newRootForResidents(t)
|
||||
defer parent.Stop()
|
||||
|
||||
fake := &outputTestDevice{name: "fakeout"}
|
||||
other := &outputTestDevice{name: "other"}
|
||||
if err := parent.io.RegisterDevice(fake); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := parent.io.RegisterDevice(other); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if _, err := parent.SpawnResident(ResidentOptions{
|
||||
ID: "r-out",
|
||||
TaskPrompt: "有情况就发到 fakeout",
|
||||
// 白名单只放行一个:验证"继承可见"不等于"绕过授权"
|
||||
AllowedOutputs: []string{"fakeout"},
|
||||
TempPath: filepath.Join(dir, "residents", "r-out", "graph.db"),
|
||||
}); err != nil {
|
||||
t.Fatalf("创建驻留子失败: %v", err)
|
||||
}
|
||||
child := parent.residents["r-out"].agent
|
||||
|
||||
// ① 看得见:修复前这里是 0(childIO 空壳)
|
||||
if caps := child.io.GetChannelCapabilities("fakeout"); caps == 0 {
|
||||
t.Fatal("驻留子看不见父的输出通道(childIO 空壳)")
|
||||
}
|
||||
// ② 发得出去:真走 dev.Execute("output", ...)
|
||||
if out := child.executeOutputSendTool(outputSendTool("fakeout", "子发来的消息")); out != "ok" {
|
||||
t.Fatalf("子发送应成功,得到 %q", out)
|
||||
}
|
||||
if len(fake.sent) != 1 {
|
||||
t.Fatalf("父通道应收到 1 次输出,得到 %d", len(fake.sent))
|
||||
}
|
||||
|
||||
// ③ 授权闸不被回退绕过:白名单外的通道照样拒绝
|
||||
if out := child.executeOutputSendTool(outputSendTool("other", "越权")); !strings.Contains(out, "未授权") {
|
||||
t.Fatalf("白名单外的通道应被拒,得到 %q", out)
|
||||
}
|
||||
if len(other.sent) != 0 {
|
||||
t.Fatal("越权输出不应真的送达")
|
||||
}
|
||||
|
||||
// ④ 工具面一致:子应生成 output_send__fakeout(含配套 _help),
|
||||
// 而**不生成**白名单外通道的工具 —— 模型看不到就不会去调。
|
||||
var names []string
|
||||
for _, td := range child.buildToolDefs() {
|
||||
entry, _ := td.(map[string]interface{})
|
||||
fn, _ := entry["function"].(map[string]interface{})
|
||||
if n, _ := fn["name"].(string); strings.HasPrefix(n, "output_send__") {
|
||||
names = append(names, n)
|
||||
}
|
||||
}
|
||||
has := func(want string) bool {
|
||||
for _, n := range names {
|
||||
if n == want {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
if !has("output_send__fakeout") || !has("output_send__fakeout_help") {
|
||||
t.Fatalf("子缺少授权通道的输出工具,得到 %v", names)
|
||||
}
|
||||
for _, n := range names {
|
||||
if strings.HasPrefix(n, "output_send__other") {
|
||||
t.Fatalf("白名单外的通道不该生成工具,得到 %v", names)
|
||||
}
|
||||
}
|
||||
|
||||
// ⑤ 实时性:父之后新登记的通道,子立刻可见(设备随资源生灭)
|
||||
late := &outputTestDevice{name: "late"}
|
||||
if err := parent.io.RegisterDevice(late); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if caps := child.io.GetChannelCapabilities("late"); caps == 0 {
|
||||
t.Fatal("父新登记的通道未实时反映到子(说明是快照而非回退)")
|
||||
}
|
||||
}
|
||||
|
||||
// 默认授权(AllowedOutputs 空)= 完整授权:子用父的全部输出通道。
|
||||
func TestResident_DefaultOutputsAreFull(t *testing.T) {
|
||||
parent, _, dir := newRootForResidents(t)
|
||||
defer parent.Stop()
|
||||
|
||||
dev := &outputTestDevice{name: "anywhere"}
|
||||
if err := parent.io.RegisterDevice(dev); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := parent.SpawnResident(ResidentOptions{
|
||||
ID: "r-full", TaskPrompt: "待命",
|
||||
TempPath: filepath.Join(dir, "residents", "r-full", "graph.db"),
|
||||
}); err != nil {
|
||||
t.Fatalf("创建驻留子失败: %v", err)
|
||||
}
|
||||
child := parent.residents["r-full"].agent
|
||||
if out := child.executeOutputSendTool(outputSendTool("anywhere", "默认授权")); out != "ok" {
|
||||
t.Fatalf("默认应完整授权,得到 %q", out)
|
||||
}
|
||||
}
|
||||
@ -104,6 +104,29 @@ type IOManager struct {
|
||||
nextReqID int64
|
||||
channelReg *ChannelRegistry
|
||||
|
||||
// parent 是"上级 IOManager"(驻留子的轻量内核指向父的内核)。
|
||||
//
|
||||
// 为什么需要:**输出通道在 io 层就是 Device**,而它们是由插件登记在**父**的
|
||||
// io 上的。驻留子有自己的 IOManager(自己的输入入口、自己的 outputCh),
|
||||
// 若只看自己那张空表,`output_send__<通道>` 会被判"通道不存在或不可用",
|
||||
// `output_list_channels` 是空的,`output_send__*` 工具也不会生成
|
||||
// —— 现场表现就是"驻留子不会说话/不会发消息"(联调实录:父侧通道装载完整、
|
||||
// 子侧 childIO 空壳)。
|
||||
//
|
||||
// 用**实时回退**而不是创建时复制快照:设备会随资源生灭(远程设备上线/掉线
|
||||
// 以分钟计),复制出来的表转瞬就过期。授权由各自的 AllowedOutputs 白名单把关,
|
||||
// 回退只解决"看得见",不解决"能不能用"。
|
||||
parent *IOManager
|
||||
|
||||
// inputRouter 决定一条输入是否被"别的 agent"接管(返回 true = 已接管)。
|
||||
//
|
||||
// 为什么放在 io:inputch 是**最基本的输入路由单位**,而**路由发生在进内核之前**
|
||||
// (docs/zh/resident-subagent-design.md §4.1)。插件注入输入的收口就在这里,
|
||||
// 所以路由必须在这里生效 —— inputch 划给某个 agent 后,输入**只流向那个 agent**,
|
||||
// 本内核根本看不到它。io 层不认识 agent,路由器由内核注入
|
||||
// (见 core.Agent.routeInputByOwner)。
|
||||
inputRouter InputRouter
|
||||
|
||||
// toolBlocks:插件工具注入多模态内容块,process.go 在下一条 tool message 时消费。
|
||||
// 用 interface{}[] 避免 import api.ContentBlock 导致的循环依赖。
|
||||
toolBlocksMu sync.Mutex
|
||||
@ -120,6 +143,72 @@ func NewIOManager() *IOManager {
|
||||
}
|
||||
}
|
||||
|
||||
// InputRouter 是输入路由器的签名。
|
||||
//
|
||||
// evt 待投递的输入事件(OutputChannel 即它的 inputch)
|
||||
// isInterrupt 该输入是中断还是排队(两者都要按归属路由)
|
||||
// 返回 true = 已被别的 agent 接管,本内核不再处理
|
||||
type InputRouter func(evt *InputEvent, isInterrupt bool) bool
|
||||
|
||||
// SetInputRouter 注入输入路由器(nil = 不路由,行为与以前完全一致)。
|
||||
func (m *IOManager) SetInputRouter(r InputRouter) {
|
||||
m.mu.Lock()
|
||||
m.inputRouter = r
|
||||
m.mu.Unlock()
|
||||
}
|
||||
|
||||
// deliverInput 是**本内核**接收一条外部输入的收口:先按 inputch 归属路由,
|
||||
// 被别的 agent 接管就不进本内核队列(划给子的 inputch,父不再收到 —— 这是「划拨」
|
||||
// 的语义,不是"父也顺便看一眼")。
|
||||
func (m *IOManager) deliverInput(evt *InputEvent, isInterrupt bool) {
|
||||
m.mu.RLock()
|
||||
router := m.inputRouter
|
||||
m.mu.RUnlock()
|
||||
if router != nil && router(evt, isInterrupt) {
|
||||
return
|
||||
}
|
||||
m.pushLocal(evt, isInterrupt)
|
||||
}
|
||||
|
||||
// DeliverRouted 把**已被路由**的事件放进本内核队列(不再二次路由)。
|
||||
// 由路由器实现调用:父把输入交给持有该 inputch 的子。
|
||||
func (m *IOManager) DeliverRouted(evt *InputEvent, isInterrupt bool) {
|
||||
m.pushLocal(evt, isInterrupt)
|
||||
}
|
||||
|
||||
func (m *IOManager) pushLocal(evt *InputEvent, isInterrupt bool) {
|
||||
if isInterrupt {
|
||||
m.interruptCh <- evt
|
||||
return
|
||||
}
|
||||
m.inputCh <- evt
|
||||
}
|
||||
|
||||
// SetParentIO 设置上级 IOManager(nil 表示无上级,行为与以前完全一致)。
|
||||
// 见 parent 字段的说明:用于驻留子继承父的输出通道/设备视图。
|
||||
func (m *IOManager) SetParentIO(p *IOManager) {
|
||||
m.mu.Lock()
|
||||
m.parent = p
|
||||
m.mu.Unlock()
|
||||
}
|
||||
|
||||
// lookupDevice 查设备:自己的登记优先,其次回退到上级。
|
||||
//
|
||||
// 先在自己锁内取快照再查上级,**不跨锁调用**(避免锁序问题)。
|
||||
func (m *IOManager) lookupDevice(name string) Device {
|
||||
m.mu.RLock()
|
||||
dev, ok := m.devices[name]
|
||||
parent := m.parent
|
||||
m.mu.RUnlock()
|
||||
if ok {
|
||||
return dev
|
||||
}
|
||||
if parent != nil {
|
||||
return parent.GetDevice(name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *IOManager) UnregisterDevice(name string) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
@ -158,9 +247,7 @@ func (m *IOManager) RegisterDevice(dev Device) error {
|
||||
}
|
||||
|
||||
func (m *IOManager) GetDevice(name string) Device {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
return m.devices[name]
|
||||
return m.lookupDevice(name)
|
||||
}
|
||||
|
||||
func (m *IOManager) StartAll() error {
|
||||
@ -195,50 +282,52 @@ func (m *IOManager) StopAll() {
|
||||
}
|
||||
|
||||
func (m *IOManager) InjectInput(source string, eventType string, payload map[string]interface{}) {
|
||||
m.inputCh <- &InputEvent{
|
||||
m.deliverInput(&InputEvent{
|
||||
RequestID: m.nextRequestID(),
|
||||
Source: source,
|
||||
Type: eventType,
|
||||
Payload: payload,
|
||||
OutputChannel: source,
|
||||
}
|
||||
}, false)
|
||||
}
|
||||
|
||||
func (m *IOManager) InjectInputSync(source string, eventType string, payload map[string]interface{}) *OutputEvent {
|
||||
ch := make(chan *OutputEvent, 1)
|
||||
m.inputCh <- &InputEvent{
|
||||
m.deliverInput(&InputEvent{
|
||||
RequestID: m.nextRequestID(),
|
||||
Source: source,
|
||||
Type: eventType,
|
||||
Payload: payload,
|
||||
ResponseCh: ch,
|
||||
OutputChannel: source,
|
||||
}
|
||||
}, false)
|
||||
// 被路由走时,回答由持有该 inputch 的 agent 写进同一个 ResponseCh
|
||||
//(§4.3:同步输入的回程是事前定好的)——所以这里照常等待。
|
||||
return <-ch
|
||||
}
|
||||
|
||||
// InjectInputTo 注入输入事件并指定输出通道
|
||||
func (m *IOManager) InjectInputTo(source, outputChannel, eventType string, payload map[string]interface{}) {
|
||||
m.inputCh <- &InputEvent{
|
||||
m.deliverInput(&InputEvent{
|
||||
RequestID: m.nextRequestID(),
|
||||
Source: source,
|
||||
Type: eventType,
|
||||
Payload: payload,
|
||||
OutputChannel: outputChannel,
|
||||
}
|
||||
}, false)
|
||||
}
|
||||
|
||||
// InjectInputSyncTo 注入输入事件(同步等待)并指定输出通道
|
||||
func (m *IOManager) InjectInputSyncTo(source, outputChannel, eventType string, payload map[string]interface{}) *OutputEvent {
|
||||
ch := make(chan *OutputEvent, 1)
|
||||
m.inputCh <- &InputEvent{
|
||||
m.deliverInput(&InputEvent{
|
||||
RequestID: m.nextRequestID(),
|
||||
Source: source,
|
||||
Type: eventType,
|
||||
Payload: payload,
|
||||
ResponseCh: ch,
|
||||
OutputChannel: outputChannel,
|
||||
}
|
||||
}, false)
|
||||
return <-ch
|
||||
}
|
||||
|
||||
@ -333,13 +422,13 @@ func (m *IOManager) InjectInterrupt(source, channel string, payload map[string]i
|
||||
payload = map[string]interface{}{}
|
||||
}
|
||||
evtType, _ := payload["type"].(string)
|
||||
m.interruptCh <- &InputEvent{
|
||||
m.deliverInput(&InputEvent{
|
||||
RequestID: m.nextRequestID(),
|
||||
Source: source,
|
||||
Type: evtType,
|
||||
Payload: payload,
|
||||
OutputChannel: channel,
|
||||
}
|
||||
}, true)
|
||||
}
|
||||
|
||||
func (m *IOManager) InjectInterruptText(source, channel, text string) {
|
||||
@ -542,6 +631,15 @@ func (m *IOManager) ExecuteTool(name string, args map[string]interface{}) (ret i
|
||||
m.mu.RUnlock()
|
||||
|
||||
if len(candidates) == 0 {
|
||||
// 自己没这个设备工具 → 看上级(驻留子的设备工具都在父的 io 上)。
|
||||
m.mu.RLock()
|
||||
parent := m.parent
|
||||
m.mu.RUnlock()
|
||||
if parent != nil {
|
||||
if ret, err := parent.ExecuteTool(name, args); err == nil {
|
||||
return ret, nil
|
||||
}
|
||||
}
|
||||
return nil, fmt.Errorf("tool %s not found", name)
|
||||
}
|
||||
defer func() {
|
||||
@ -574,10 +672,22 @@ type ChannelInfo struct {
|
||||
|
||||
func (m *IOManager) ListChannels() []ChannelInfo {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
own := make(map[string]Device, len(m.devices))
|
||||
for name, dev := range m.devices {
|
||||
own[name] = dev
|
||||
}
|
||||
parent := m.parent
|
||||
m.mu.RUnlock()
|
||||
|
||||
// 自己的登记优先(子侧可覆盖/屏蔽同名通道),随后并入上级的可见通道。
|
||||
// 去重按**名字**:同名即视为同一个通道,不重复列举。
|
||||
seen := make(map[string]bool, len(own))
|
||||
var list []ChannelInfo
|
||||
for _, dev := range m.devices {
|
||||
appendDev := func(dev Device) {
|
||||
if seen[dev.Name()] {
|
||||
return
|
||||
}
|
||||
seen[dev.Name()] = true
|
||||
list = append(list, ChannelInfo{
|
||||
Name: dev.Name(),
|
||||
Type: dev.Type(),
|
||||
@ -586,13 +696,23 @@ func (m *IOManager) ListChannels() []ChannelInfo {
|
||||
OutputCaps: dev.OutputCapabilities(),
|
||||
})
|
||||
}
|
||||
for _, dev := range own {
|
||||
appendDev(dev)
|
||||
}
|
||||
if parent != nil {
|
||||
for _, ch := range parent.ListChannels() {
|
||||
if seen[ch.Name] {
|
||||
continue
|
||||
}
|
||||
seen[ch.Name] = true
|
||||
list = append(list, ch)
|
||||
}
|
||||
}
|
||||
return list
|
||||
}
|
||||
|
||||
func (m *IOManager) GetChannelCapabilities(channel string) OutputCapability {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
if dev, ok := m.devices[channel]; ok {
|
||||
if dev := m.lookupDevice(channel); dev != nil {
|
||||
return dev.OutputCapabilities()
|
||||
}
|
||||
return 0
|
||||
|
||||
74
internal/agent/io/inputroute_test.go
Normal file
74
internal/agent/io/inputroute_test.go
Normal file
@ -0,0 +1,74 @@
|
||||
package io
|
||||
|
||||
import "testing"
|
||||
|
||||
// 输入路由:路由器说"已被别的 agent 接管"时,事件**不得**进本内核队列。
|
||||
//
|
||||
// 语义(设计 §4.1):inputch 是可分配资源,划给某个 agent 后输入只流向它 ——
|
||||
// "父也顺便看到一份"是错的。
|
||||
func TestInputRouter_TakesOverExclusively(t *testing.T) {
|
||||
m := NewIOManager()
|
||||
var got []*InputEvent
|
||||
var sawInterrupt bool
|
||||
m.SetInputRouter(func(evt *InputEvent, isInterrupt bool) bool {
|
||||
got = append(got, evt)
|
||||
sawInterrupt = sawInterrupt || isInterrupt
|
||||
return true // 全部接管
|
||||
})
|
||||
|
||||
m.InjectInputTo("plugin-x", "sub/in", "text", map[string]interface{}{"content": "a"})
|
||||
m.InjectInterruptTextOpts("plugin-x", "sub/in", "b", InjectOptions{})
|
||||
|
||||
if len(got) < 2 {
|
||||
t.Fatalf("路由器应被调用(含中断路径),实际 %d 次", len(got))
|
||||
}
|
||||
if n := len(m.InputChan()); n != 0 {
|
||||
t.Fatalf("被接管的排队输入不得进本内核队列,实际 %d 条", n)
|
||||
}
|
||||
if !sawInterrupt {
|
||||
t.Fatal("中断注入也必须经过路由(否则中断会绕过 inputch 归属直投父)")
|
||||
}
|
||||
if got[0].OutputChannel != "sub/in" {
|
||||
t.Fatalf("路由器应拿到事件的 inputch,得到 %q", got[0].OutputChannel)
|
||||
}
|
||||
}
|
||||
|
||||
// 路由器放行(返回 false)或未设置时,行为与以前完全一致。
|
||||
func TestInputRouter_PassthroughKeepsOldBehaviour(t *testing.T) {
|
||||
m := NewIOManager()
|
||||
calls := 0
|
||||
m.SetInputRouter(func(evt *InputEvent, isInterrupt bool) bool { calls++; return false })
|
||||
|
||||
m.InjectInputTo("plugin-x", "sub/in", "text", map[string]interface{}{"content": "a"})
|
||||
if calls != 1 {
|
||||
t.Fatalf("路由器应被调用一次,实际 %d", calls)
|
||||
}
|
||||
if n := len(m.InputChan()); n != 1 {
|
||||
t.Fatalf("放行的输入应进本内核队列,实际 %d 条", n)
|
||||
}
|
||||
if _, ok := <-m.InputChan(); !ok {
|
||||
t.Fatal("队列应可读")
|
||||
}
|
||||
|
||||
// 未设路由器:直接入队(历史行为)
|
||||
m2 := NewIOManager()
|
||||
m2.InjectInterruptText("plugin-x", "sub/in", "c")
|
||||
if n := len(m2.InputInterruptChan()); n != 1 {
|
||||
t.Fatalf("未设路由器时中断应直接入队,实际 %d 条", n)
|
||||
}
|
||||
}
|
||||
|
||||
// DeliverRouted 是不再二次路由的投递口(路由器实现把事件交给持有者)。
|
||||
func TestDeliverRouted_SkipsSecondRouting(t *testing.T) {
|
||||
m := NewIOManager()
|
||||
routerCalls := 0
|
||||
m.SetInputRouter(func(evt *InputEvent, isInterrupt bool) bool { routerCalls++; return true })
|
||||
|
||||
m.DeliverRouted(&InputEvent{OutputChannel: "sub/in"}, false)
|
||||
if routerCalls != 0 {
|
||||
t.Fatalf("DeliverRouted 不应再触发路由(会成环),实际 %d 次", routerCalls)
|
||||
}
|
||||
if n := len(m.InputChan()); n != 1 {
|
||||
t.Fatalf("应已入队,实际 %d 条", n)
|
||||
}
|
||||
}
|
||||
102
internal/agent/io/parentio_test.go
Normal file
102
internal/agent/io/parentio_test.go
Normal file
@ -0,0 +1,102 @@
|
||||
package io
|
||||
|
||||
import "testing"
|
||||
|
||||
// 上级回退:驻留子的轻量内核有自己的 IOManager,但输出通道(io 里的 Device)
|
||||
// 是插件登记在**父**的 io 上的。子若看不见它们,`output_send__<通道>` 会被判
|
||||
// "通道不存在或不可用"、`output_list_channels` 为空 —— 现场联调实录
|
||||
// 「父侧通道装载完整、子侧 childIO 空壳」。
|
||||
func TestIOManagerParentFallback(t *testing.T) {
|
||||
parent := NewIOManager()
|
||||
if err := parent.RegisterDevice(&mockDevice{name: "qq", devType: DeviceOutput, caps: CapText}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
child := NewIOManager()
|
||||
// 未挂上级时行为与以前完全一致(不能悄悄多出通道)
|
||||
if got := child.GetChannelCapabilities("qq"); got != 0 {
|
||||
t.Fatalf("无上级时不应看见父的通道,得到 %v", got)
|
||||
}
|
||||
if n := len(child.ListChannels()); n != 0 {
|
||||
t.Fatalf("无上级时通道数应为 0,得到 %d", n)
|
||||
}
|
||||
|
||||
child.SetParentIO(parent)
|
||||
if got := child.GetChannelCapabilities("qq"); got != CapText {
|
||||
t.Fatalf("挂上级后应看见父通道能力 CapText,得到 %v", got)
|
||||
}
|
||||
if dev := child.GetDevice("qq"); dev == nil || dev.Name() != "qq" {
|
||||
t.Fatalf("GetDevice 未回退到父: %v", dev)
|
||||
}
|
||||
if n := len(child.ListChannels()); n != 1 {
|
||||
t.Fatalf("ListChannels 未回退到父,得到 %d 条", n)
|
||||
}
|
||||
|
||||
// **实时**回退而非快照:父后来登记的通道,子立刻可见。
|
||||
// (设备随资源生灭 —— 远程设备上线/掉线以分钟计,快照一分钟就过期)
|
||||
if err := parent.RegisterDevice(&mockDevice{name: "newdev", devType: DeviceOutput, caps: CapImage}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := child.GetChannelCapabilities("newdev"); got != CapImage {
|
||||
t.Fatalf("子应实时看见父新登记的通道,得到 %v", got)
|
||||
}
|
||||
|
||||
// 父掉线注销后,子也立刻看不见(不是复制出来的旧表)
|
||||
parent.UnregisterDevice("newdev")
|
||||
if got := child.GetChannelCapabilities("newdev"); got != 0 {
|
||||
t.Fatalf("父注销后子不应再看见,得到 %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// 自己的登记优先:子可以覆盖/屏蔽同名通道,父的登记不会重复列出。
|
||||
func TestIOManagerOwnDeviceWins(t *testing.T) {
|
||||
parent := NewIOManager()
|
||||
if err := parent.RegisterDevice(&mockDevice{name: "ch", devType: DeviceOutput, caps: CapText}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
child := NewIOManager()
|
||||
child.SetParentIO(parent)
|
||||
if err := child.RegisterDevice(&mockDevice{name: "ch", devType: DeviceOutput, caps: CapImage}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if got := child.GetChannelCapabilities("ch"); got != CapImage {
|
||||
t.Fatalf("同名时自己的登记应优先,得到 %v", got)
|
||||
}
|
||||
list := child.ListChannels()
|
||||
if len(list) != 1 {
|
||||
t.Fatalf("同名通道不应重复列出,得到 %d 条", len(list))
|
||||
}
|
||||
if list[0].OutputCaps != CapImage {
|
||||
t.Fatalf("列出的应是子自己的那条,得到 %v", list[0].OutputCaps)
|
||||
}
|
||||
}
|
||||
|
||||
// 设备工具(io.ExecuteTool)同样回退:子的设备工具都在父的 io 上。
|
||||
func TestIOManagerExecuteToolFallsBackToParent(t *testing.T) {
|
||||
parent := NewIOManager()
|
||||
called := 0
|
||||
if err := parent.RegisterDevice(&mockDevice{
|
||||
name: "dev", devType: DeviceIO,
|
||||
tools: []ToolDef{{Name: "dev_do", Description: "干点什么"}},
|
||||
executeFn: func(tool string, args map[string]interface{}) (interface{}, error) {
|
||||
called++
|
||||
return "parent-done", nil
|
||||
},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
child := NewIOManager()
|
||||
if _, err := child.ExecuteTool("dev_do", nil); err == nil {
|
||||
t.Fatal("无上级时不该能执行父的设备工具")
|
||||
}
|
||||
child.SetParentIO(parent)
|
||||
got, err := child.ExecuteTool("dev_do", map[string]interface{}{"x": 1})
|
||||
if err != nil {
|
||||
t.Fatalf("应回退到父执行: %v", err)
|
||||
}
|
||||
if got != "parent-done" || called != 1 {
|
||||
t.Fatalf("执行结果=%v called=%d", got, called)
|
||||
}
|
||||
}
|
||||
@ -28,12 +28,14 @@ var (
|
||||
//
|
||||
// ❗main 上此值始终是**下一个未发布中版本**,不随 patch 发布变动
|
||||
//(见 docs/git-branching.md §2.1);已发布的版本号看对应的 release/vX.Y.x 与 tag。
|
||||
// 1.3.8:inputch 划给子后输入只流向子(补上"进内核之前"的输入路由)。
|
||||
// 1.3.7:驻留子继承父的输出通道(此前子侧 childIO 空壳 ⇒ 子不会发消息)。
|
||||
// 1.3.6:人格文本不再在播种时固化版本 + 存量实例一次性去版本化(生产实例
|
||||
// 曾自报 v1.0.3);系统提示词支持 {{kernel_version}} 等占位符。
|
||||
// 1.3.5:系统提示词(人格卡)支持版本占位符 —— 人格卡是配置项,写死版本号
|
||||
// 会随发版说谎(线上写 v1.0.3、内核 1.3.x,agent 就自报 1.0.3)。
|
||||
// 支持 {{kernel_version}} / {{kernel_commit}} / {{sdk_version}}。
|
||||
Version = "1.3.6"
|
||||
Version = "1.3.8"
|
||||
|
||||
// Commit 是构建时的 Git commit hash。
|
||||
Commit = "unknown"
|
||||
|
||||
Reference in New Issue
Block a user