mirror of
https://gitcode.com/JianFeeeee/HomeAgent.git
synced 2026-11-01 14:57:38 +00:00
## rtchild(R1–R13)
第三种、**独立**的子 agent 类型,面向语音/视频通话:内核只要文本流,
不定音频(TTS/播放由插件负责)。
- R1 CapRT 能力位 + AgentConfig.IsRealtime;AssignRealtime 两侧校验
- R2 rtSlot 单槽覆盖(latest-wins,从不排队)
- R3 独立 ctx + rtLoop + SpawnRTChild/StopRTChild
- R4 ChatStream 逐块 → outputch(rt).Execute(text)
- R5 打断 = 原地截断,不重试
- R6 工具执行期不可打断(suppressedCancels 让守卫可观测)
- R7 普通上下文 + 窗口裁剪(旧内容不进模型,**原文保留**)
- R9 CloseRTChild → L4 信号 + rt_transcript 按需分页取
- R10 notify_parent(L4,注册一次,停即注销)
- R11 闲置零 token
- R13 rt_children 管理工具(父专属)
刻意**不做** rtPage/anchor/degraded_resets(过设计,已裁定);
不用四级中断阶梯(preemptCooldown+同级不抢占会让 ~75% 的 rt 打断
静默退化为排队)。
## 四类 agent 各自可配模型源
core.agent.llm.{main,resident,rt,child}_provider,语义是**优先不是独占**:
该源排到候选链最前,其余源仍作回退。硬锁定会让"首选源抖一下"变成
"这个 agent 彻底不工作",而多源回退链正是本仓为此建立的机制。
名字写错 ⇒ 回退默认源 + 记日志(不静默)。子 agent 未配置时继承父的。
★ 顺带修掉一个真缺陷:spawn.go 原来直接 a.provider.Chat(),
**普通子 agent 完全绕过 provider 回退链** —— 它是唯一绕过的地方:
默认源抖一次整条子任务就"执行失败",而主 agent 同刻能自动换源。
## 驻留子残余任务四态 + 通道三态
残余任务:keep / takeover(接手,keep 的明确别名)/ stash(暂存到各自
原通道)/ drop。stash 必须**逐条按各自 OutputChannel 归位** —— 一个子
可能同时收 qq 和 webui,混存会让"接回 qq 的人"拿到本该给 webui 的活。
通道:release(零值,向后兼容)/ suspend(挂起,暂存保留)/ takeover
(接回父并立即释放暂存)。原来是无条件 release,于是只有两种坏结局:
通道一直没人分配(消息无人处理且无提示),或刚好被别的 agent 抢到。
一次定完不留窗口:FinishResidentWith → DestroyResidentWith →
teardownResidentWith。任一环退回不带 disp 的旧函数,disp 就被丢掉、
通道被无条件释放 —— 而 stash 的暂存正挂在那条通道上(实际踩过)。
## 修复"手写字段白名单"丢值(7 处)
同一类缺陷:不传整个结构体,而是手写一份"允许通过的字段清单"。
危险在于**写漏了不报错** —— 字段静默归零,故障出现在很远的地方。
- corehandler.go outputRegister: ChannelDef{NoMemory,Cleaner} → 整体传
- pubSdkInjectOpts: 逐字段摊平丢 ScenePolicy/SecurityProfile → 收整个 injectParams
- injectParams/injectMediaParams: 结构本身缺字段 → 补齐 + asInjectParams()
- 配套反射判据 TestSegment_RoundTripEveryField(取代手写断言,
原判据漏了 Phase/LLMText/FinalText/ToolCalls/ExtraKeyMediaBlocks/ExtraBag)
## 压缩偏离设计
CompressResident 原为截断,与设计(LLM 摘要替换)不符。改走
PlanCompaction → summarizeForCompaction(用子自己的 provider)→
ApplyCompaction,失败回退 TrimKeepRecent。顺带修 ApplyCompaction 的
锁重入 panic 与双重解锁。
并修一处真实生产数据竞争:ctxFullSignaled 由父 goroutine 写、
子调度 goroutine 读,加 ctxFullMu。
## 判据
新增约 70 条。全部验证过能变红(变异测试),包括:
- TestSegment_RoundTripEveryField 的防腐蚀:fullStageContext 反射断言
每个字段非零,否则新字段永远不会被覆盖("假绿")
- TestPreferredProvider_PutsSourceFirstAndKeepsFallbacks 成对断言
"在首位且回退仍在"—— 只断言前者的话,硬锁定也会绿
## 判据自身的坑(两次偶发红,都不是产品缺陷)
1. SpawnResident 末尾 Start(),子会在两次 enqueue 之间取走一条
→ "暂存 0 条"。修法:cancel + waitSchedulerStopped。
(offload_test.go 早有记录,我没先读就重踩了一遍)
2. TaskPrompt 异步投递,可能在清空队列之后才到 → "多 1 条"。
靠探针打印内容才认出是 TaskPrompt。修法:本文件用 spawnQuietResident。
go build/vet/gofmt 干净;go test ./... -count=1 -race = 62 包 ok / 0 FAIL / 0 RACE
244 lines
8.0 KiB
Go
244 lines
8.0 KiB
Go
package core
|
||
|
||
import (
|
||
"encoding/json"
|
||
"fmt"
|
||
"log"
|
||
"strings"
|
||
)
|
||
|
||
func (a *Agent) executePluginReload() string {
|
||
if a.pluginReg == nil {
|
||
return "插件系统未启用"
|
||
}
|
||
msg, err := a.pluginReg.Reload(a.pluginDir)
|
||
if err != nil {
|
||
return fmt.Sprintf("插件重载失败: %v", err)
|
||
}
|
||
return msg
|
||
}
|
||
|
||
func (a *Agent) autoReloadPlugins() {
|
||
if a.pluginReg == nil {
|
||
return
|
||
}
|
||
for _, name := range a.pluginHealth.pendingReloads() {
|
||
if !a.pluginReg.AutoRestartEnabled(name) {
|
||
log.Printf("[agent] skip auto-reload plugin %s: auto-restart disabled by plugin", name)
|
||
continue
|
||
}
|
||
log.Printf("[agent] auto-reloading unhealthy plugin: %s", name)
|
||
if a.stageHost != nil {
|
||
a.stageHost.UnregisterPluginTools(name)
|
||
}
|
||
if err := a.pluginReg.ReloadOne(name); err != nil {
|
||
log.Printf("[agent] auto-reload plugin %s failed: %v", name, err)
|
||
} else {
|
||
a.pluginHealth.markReloaded(name)
|
||
log.Printf("[agent] plugin %s reloaded successfully", name)
|
||
}
|
||
}
|
||
}
|
||
|
||
// builtinToolOwner 是**内置工具的显式归属表**。
|
||
//
|
||
// ★ 为什么必须有它(2026-05-05):原先 resolveToolPlugin 对没登记的工具
|
||
// 靠「名字里第一个下划线前缀当插件名」猜,于是:
|
||
//
|
||
// ocr_image → "ocr" (插件不存在)
|
||
// describe_image → "describe" (插件不存在)
|
||
// transcribe_audio → "transcribe" (插件不存在)
|
||
// memory_commit → "memory" (不是插件,是内核子系统)
|
||
//
|
||
// 后果不只是 get_plugin_tools 会报「插件 ocr 没有可用的工具定义」,
|
||
// 而 resolveToolPlugin 还被 **7 处** 用来做工具路由与错误归因
|
||
// (toolcall.go:42 / task.go:710,892,939 / tooldefs.go:266),
|
||
// 猜错会把归属报给插件健康与监控,指向不存在的名字。
|
||
//
|
||
// 形态:**显式列举**而不是前缀规则。像 memory_* / doc_* / person_* 这些
|
||
// 根本不是插件,靠规则永远猜不对。
|
||
var builtinToolOwner = map[string]string{
|
||
// 记忆子系统(内核能力,不是插件)
|
||
"stablemem_recall": "core", "stablemem_commit": "core", "stablemem_merge": "core",
|
||
"stablemem_purge": "core", "stablemem_edit": "core", "stablemem_delete_entity": "core",
|
||
"stablemem_block_merge": "core", "stablemem_introspect": "core",
|
||
// 知识库
|
||
"knowledge_search": "core", "knowledge_create": "core", "knowledge_list": "core",
|
||
"knowledge_delete": "core", "knowledge_import_dir": "core",
|
||
// 文档记忆
|
||
"coldcontext_query": "core", "coldcontext_commit": "core",
|
||
// 社交 / 人格
|
||
"person_query": "core", "person_set_trait": "core", "person_relate": "core",
|
||
"persona_set": "core",
|
||
// 通道 / 调度 / 驻留子
|
||
"output_send__": "core", "output_list_channels": "core",
|
||
"input_channels": "core", "inputch_note": "core",
|
||
"spawn_child": "core", "child_result": "core", "notify_parent": "core",
|
||
"resident_agents": "core",
|
||
// rtchild 上下文交接的拉取入口(用户裁定 2026-10-30:走 contextfull 式中断,
|
||
// 主 agent 自行选择保留哪些内容)。归 core:它是内核原语,不是插件能力。
|
||
"rt_transcript": "core",
|
||
"rt_children": "core",
|
||
// LLM 源 / 插件管理
|
||
"llm_list_sources": "core", "llm_set_source": "core", "llm_current_source": "core",
|
||
"plgreload": "core", "get_plugin_tools": "core", "list_devices": "core",
|
||
"devicedetect": "core", "device_ctl_status": "core", "device_ctl_cmdrun": "core",
|
||
// 安全模块的变量库(内核能力,不是插件)
|
||
"secret_submit": "core", "secret_list": "core", "secret_forget": "core",
|
||
"device_ctl_cmdresult": "core", "screensee": "core",
|
||
}
|
||
|
||
func (a *Agent) resolveToolPlugin(name string) string {
|
||
if a.stageHost != nil {
|
||
if plugin := a.stageHost.ToolPlugin(name); plugin != "" {
|
||
return plugin
|
||
}
|
||
}
|
||
// ★ 显式归属表优先于「按下划线猜」。
|
||
// 未登记的内置工具归 core,而不是编出一个可能不存在的插件名。
|
||
if owner, ok := builtinToolOwner[name]; ok {
|
||
return owner
|
||
}
|
||
// 前缀规则只对「确实是 <plugin>_<tool>」形态的名字有意义
|
||
// (例如外部插件的 email_email_list)。但它对内核自带的名字会造出
|
||
// 假插件,所以限制在「该前缀是一个**已注册**的插件」时才采纳。
|
||
if idx := strings.IndexByte(name, '_'); idx > 0 {
|
||
cand := name[:idx]
|
||
if a.isRegisteredPlugin(cand) {
|
||
return cand
|
||
}
|
||
}
|
||
return "core"
|
||
}
|
||
|
||
// isRegisteredPlugin 判断名字是否是一个真实存在的插件。
|
||
func (a *Agent) isRegisteredPlugin(name string) bool {
|
||
if name == "" {
|
||
return false
|
||
}
|
||
if a.pluginReg != nil {
|
||
for _, n := range a.pluginReg.List() {
|
||
if n == name {
|
||
return true
|
||
}
|
||
}
|
||
}
|
||
if a.stageHost != nil {
|
||
for _, d := range a.stageHost.GetToolDefs() {
|
||
p := d.Plugin
|
||
if p == "" {
|
||
p = a.resolveToolPlugin(d.Name)
|
||
}
|
||
if p == name {
|
||
return true
|
||
}
|
||
}
|
||
}
|
||
return false
|
||
}
|
||
|
||
// executeGetPluginTools 返回指定插件的完整工具定义(名称/参数/用途)。
|
||
// 支持按插件名拉取, 未指定时返回全部插件的工具摘要。
|
||
func (a *Agent) executeGetPluginTools(pluginName string) string {
|
||
type toolItem struct {
|
||
name, desc string
|
||
params interface{}
|
||
}
|
||
var items []toolItem
|
||
|
||
// 收集 StageHost(SDK 插件)工具
|
||
if a.stageHost != nil {
|
||
for _, d := range a.stageHost.GetToolDefs() {
|
||
plg := d.Plugin
|
||
if plg == "" {
|
||
plg = a.resolveToolPlugin(d.Name)
|
||
}
|
||
if pluginName != "" && plg != pluginName {
|
||
continue
|
||
}
|
||
items = append(items, toolItem{d.Name, d.Description, d.Parameters})
|
||
}
|
||
}
|
||
// 收集 IOManager(设备/通道)工具
|
||
if a.io != nil {
|
||
for _, d := range a.io.GetAllTools() {
|
||
plg := a.resolveToolPlugin(d.Name)
|
||
if pluginName != "" && plg != pluginName {
|
||
continue
|
||
}
|
||
items = append(items, toolItem{d.Name, d.Description, d.Parameters})
|
||
}
|
||
}
|
||
// ★★ 收集**内置工具**(2026-05-05)。
|
||
//
|
||
// 原实现只收 StageHost(SDK 插件) 与 IOManager(设备) 两处,
|
||
// 而 describe_image / ocr_image / memory_recall / knowledge_* 等
|
||
// 都是内核 buildToolDefs 里直接 append 的 ⇒ **一条都数不到**。
|
||
// 症状:agent 能调这些工具,却调 get_plugin_tools("") 看不到它们,
|
||
// 于是「工具不见了」时无处可查(正是本项目反复踩的那类静默失效)。
|
||
//
|
||
// 以 buildToolDefs() 为**单一真相源** —— 它就是发给模型的那份工具表,
|
||
// 这里不再维护第二份清单(第二份必然会漂移)。
|
||
seen := map[string]bool{}
|
||
for _, it := range items {
|
||
seen[it.name] = true
|
||
}
|
||
for _, raw := range a.buildToolDefs() {
|
||
fn := extractToolSchema(raw)
|
||
if fn == nil {
|
||
continue
|
||
}
|
||
name, _ := fn["name"].(string)
|
||
if name == "" || seen[name] {
|
||
continue
|
||
}
|
||
// 归属:设备/通道工具已在上面收过;剩下的按显式表(或 core)算。
|
||
plg := a.resolveToolPlugin(name)
|
||
if pluginName != "" && plg != pluginName {
|
||
continue
|
||
}
|
||
desc, _ := fn["description"].(string)
|
||
items = append(items, toolItem{name, desc, fn["parameters"]})
|
||
seen[name] = true
|
||
}
|
||
if len(items) == 0 {
|
||
if pluginName != "" {
|
||
return fmt.Sprintf("插件 %s 没有可用的工具定义(它可能未加载/已禁用/已崩溃;用 get_plugin_tools(\"\") 看全量)", pluginName)
|
||
}
|
||
return "当前没有可用的工具定义"
|
||
}
|
||
var sb strings.Builder
|
||
if pluginName == "" {
|
||
sb.WriteString(fmt.Sprintf("共 %d 个工具:\n", len(items)))
|
||
} else {
|
||
sb.WriteString(fmt.Sprintf("插件 %s 共 %d 个工具:\n", pluginName, len(items)))
|
||
}
|
||
for _, it := range items {
|
||
sb.WriteString(fmt.Sprintf("\n### %s\n", it.name))
|
||
if it.desc != "" {
|
||
sb.WriteString(it.desc + "\n")
|
||
}
|
||
if it.params != nil {
|
||
if b, err := json.Marshal(it.params); err == nil && len(b) < 600 {
|
||
sb.WriteString("参数: " + string(b) + "\n")
|
||
}
|
||
}
|
||
}
|
||
return sb.String()
|
||
}
|
||
|
||
// extractToolSchema 从 buildToolDefs 的一项里取出 function 体。
|
||
// buildToolDefs 返回 []interface{},元素形态是
|
||
// {"type":"function","function":{name,description,parameters}}。
|
||
func extractToolSchema(raw interface{}) map[string]interface{} {
|
||
m, ok := raw.(map[string]interface{})
|
||
if !ok {
|
||
return nil
|
||
}
|
||
fn, ok := m["function"].(map[string]interface{})
|
||
if !ok {
|
||
return nil
|
||
}
|
||
return fn
|
||
}
|