mirror of
https://gitcode.com/JianFeeeee/HomeAgent.git
synced 2026-10-15 12:15:16 +00:00
feat(multimodal): 多模态工具移出内核为内置插件 + get_plugin_tools 收编为内核服务
## 背景 README 第一原则:「内核职责限定在 LLM 编排、记忆管理与知识检索; 所有 IO 能力由插件实现」,而「文件读取」正在 IO 列表里。 describe_image / ocr_image / transcribe_audio 读本地文件却住在内核进程内 ——无沙箱、无能力面、无审计,正是 capability.go 那套权限梯度要防的事。 ## 本次改动 ### 1. 多模态工具移出内核(internal/plugins/multimodal) - 新增内置插件,注册 describe_image / transcribe_audio / ocr_image - 媒体来源支持 path(设备/工具回传,如 screensee 的 file)与 digest(CAS) - 失败一律以 error 上抛,不渲染成普通文本(延续 screensee 的失败传播纪律) - ocr_image 的描述明说「不是专用 OCR 引擎」:它只是用视觉模型读字, 真 OCR 在 internal/nlp 的 ONNX 未接入。名字承诺大于实现会让模型误判精度。 内核侧:删除 media.go 整文件(9 函数,全部零引用)、3 个 dispatch case、 3 个工具定义。 **留在内核**:input 通路(用户直传媒体直接拼进本轮 LLM 请求)—— 那是「输入即上下文」,不是工具调用。 ### 2. get_plugin_tools 收编为内核完整服务 原先它只收 StageHost + IOManager 两处,而三个媒体工具、memory_*、 knowledge_*、spawn_child 等全是内核 buildToolDefs 里直接 append 的 ——一条都数不到。agent 能调这些工具,却调 get_plugin_tools 看不见它们。 - 以 buildToolDefs()(发给模型的那份工具表)为单一真相源 - 新增 builtinToolOwner 显式归属表:内置工具恒为 core - resolveToolPlugin 的下划线前缀猜测限定在「该前缀是已注册插件」时才采纳, 避免 ocr_image→"ocr"、memory_commit→"memory" 这类幽灵归属(7 处调用点依赖它) ## 判据 新增 plugin_tools_service_test.go、multimodal_departed_test.go、 multimodal/plugin_test.go。三个结构判据经变异自证会红: 1. 提示词改回「请使用 describe_image 工具」→ 仍出现该名 ⇒ 红 ★ 这条抓到了真问题:eventloop.go 的媒体提示词仍在叫模型调旧工具名, 而媒体 block 其实已内联给模型,且新工具需要 path/digest(用户直传都没有) ⇒ 模型照做必然失败。已修:改为「已随本消息附上,请直接查看」。 2. 内核为多模态加一个 os.ReadFile → 红(比「名字没出现」更强) 3. core 反向 import 插件 → 红(迁移而非删除,且守住分层) ## 验证 - go build ./... / go vet / go test ./internal/... 全绿 - go test -race ./internal/agent/core/ ./internal/plugins/multimodal/ 无数据竞争 - 部署后:39 插件加载、0 panic/fatal、0 非空 error - 三个工具注册归属为 plugin=multimodal(不是 inferToolPlugin 猜的 describe) - graph.db integrity ok,blocks 2787 / relations 980 未动 - 快照 /home/newqqagent/memory/pre-multimodal-plugin-20261006-090541/ - 二进制备份 /tmp/homed.bak-mmplugin 一并包含此前已验证未提交的三处静默失效修复: - MCP MCPCallResult.IsError 丢失(空结果伪装成功) - DeleteEntity 谎报删除 - screensee 谎报成功 + 截图诊断(尺寸/magic/sha) Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@ -292,19 +292,19 @@ type AgentConfig struct {
|
||||
//
|
||||
// nil 或空 = **完整授权**(默认);非空 = 白名单,只允许列出的输出通道。
|
||||
// 父 agent 创建驻留子时用它收窄子的输出能力。
|
||||
AllowedOutputs []string
|
||||
PluginDir string
|
||||
DistillInterval time.Duration
|
||||
ArchiveInterval time.Duration // 冷文档归档间隔(L2→L3),0 则使用 DistillInterval
|
||||
ReviewInterval time.Duration // 关系复审间隔,0 则使用 DistillInterval
|
||||
MergeInterval time.Duration // 实体合并检测间隔,0 则使用 DistillInterval
|
||||
MaxContextSize int // 活跃上下文最大条数,超出按相关性裁剪
|
||||
AllowedOutputs []string
|
||||
PluginDir string
|
||||
DistillInterval time.Duration
|
||||
ArchiveInterval time.Duration // 冷文档归档间隔(L2→L3),0 则使用 DistillInterval
|
||||
ReviewInterval time.Duration // 关系复审间隔,0 则使用 DistillInterval
|
||||
MergeInterval time.Duration // 实体合并检测间隔,0 则使用 DistillInterval
|
||||
MaxContextSize int // 活跃上下文最大条数,超出按相关性裁剪
|
||||
|
||||
// CtxTuning 是上下文预算的可调参数。零值 ⇒ 使用历史默认(与硬编码时代一致)。
|
||||
//
|
||||
// 为何必须能从配置传进来:这些阈值原本写死在 ComputeTokenBudget 里,
|
||||
// 界面改不了、不同窗口的实例也没法各自调优(详见 ContextTuning 的注释)。
|
||||
CtxTuning ContextTuning
|
||||
CtxTuning ContextTuning
|
||||
ContextSavePath string // 上下文持久化路径,空则不持久化
|
||||
EmbeddingModelPath string // 预训练词嵌入模型路径(word2vec 文本格式),空则不使用
|
||||
Embedder *memory.StaticEmbedder // 共享词嵌入实例;nil 时按 EmbeddingModelPath 自建
|
||||
|
||||
@ -279,12 +279,21 @@ func (a *Agent) mediaToBlocks(payload map[string]interface{}, mediaType string,
|
||||
case "image":
|
||||
desc = a.inputCfg.Image.DescribePrompt
|
||||
if desc == "" {
|
||||
desc = fmt.Sprintf("从 %s 收到了一张图片,请使用 describe_image 工具查看详情。", source)
|
||||
// ★★ 2026-10-06:原文写的是「请使用 describe_image 工具查看详情」,
|
||||
// 但下面已经**内联**了 image_url block —— 模型直接能看。
|
||||
// 更糟的是:该工具已于本日移出为内置插件 multimodal,
|
||||
// 它需要 path 或 digest,而用户直传的图片两者都没有 ⇒
|
||||
// 模型照着提示词调它,必然拿到「没有可处理的媒体」错误。
|
||||
desc = fmt.Sprintf("从 %s 收到了一张图片(已随本消息附上,请直接查看)。", source)
|
||||
}
|
||||
case "audio":
|
||||
desc = a.inputCfg.Audio.DescribePrompt
|
||||
if desc == "" {
|
||||
desc = fmt.Sprintf("从 %s 收到了一段音频,请使用 transcribe_audio 工具查看内容。", source)
|
||||
// 同上:audio_url block 已内联。不要指示调 transcribe_audio
|
||||
// (它现在需要 path/digest);若模型本身不处理音频,
|
||||
// 应如实告知用户,而不是调一个注定失败的工具。
|
||||
desc = fmt.Sprintf("从 %s 收到了一段音频(已随本消息附上)。"+
|
||||
"若你能直接处理音频请转写;若不能,请如实告知,不要编造内容。", source)
|
||||
}
|
||||
}
|
||||
blocks = append(blocks, agentAPI.ContentBlock{Type: "text", Text: desc})
|
||||
|
||||
@ -1,95 +0,0 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
agentAPI "gitcode.com/JianFeeeee/HomeAgent/internal/agent/api"
|
||||
)
|
||||
|
||||
func (a *Agent) mediaDataURL(defaultMime string) string {
|
||||
if a.pendingMedia == nil {
|
||||
return ""
|
||||
}
|
||||
data, _ := a.pendingMedia["data"].(string)
|
||||
mime, _ := a.pendingMedia["mime"].(string)
|
||||
url, _ := a.pendingMedia["url"].(string)
|
||||
if data != "" {
|
||||
if mime == "" {
|
||||
mime = defaultMime
|
||||
}
|
||||
return "data:" + mime + ";base64," + data
|
||||
}
|
||||
return url
|
||||
}
|
||||
|
||||
func (a *Agent) mediaRequest(p agentAPI.Provider, mime, emptyPendingMsg, emptyDataMsg, prompt, resultPrefix string, maxTokens int, blockType string, detail string) string {
|
||||
if a.pendingMedia == nil {
|
||||
return emptyPendingMsg
|
||||
}
|
||||
url := a.mediaDataURL(mime)
|
||||
if url == "" {
|
||||
return emptyDataMsg
|
||||
}
|
||||
msg := agentAPI.Message{
|
||||
Role: "user",
|
||||
Blocks: []agentAPI.ContentBlock{
|
||||
{Type: "text", Text: prompt},
|
||||
},
|
||||
}
|
||||
if blockType == "image_url" {
|
||||
msg.Blocks = append(msg.Blocks, agentAPI.ContentBlock{
|
||||
Type: "image_url",
|
||||
ImageURL: &agentAPI.ImageURL{URL: url, Detail: detail},
|
||||
})
|
||||
} else {
|
||||
msg.Blocks = append(msg.Blocks, agentAPI.ContentBlock{
|
||||
Type: "audio_url",
|
||||
AudioURL: &agentAPI.AudioURL{URL: url},
|
||||
})
|
||||
}
|
||||
return a.mediaChat(p, msg, resultPrefix, maxTokens)
|
||||
}
|
||||
|
||||
func (a *Agent) mediaChat(p agentAPI.Provider, msg agentAPI.Message, resultPrefix string, maxTokens int) string {
|
||||
ctx, cancel := context.WithTimeout(a.ctx, 120*time.Second)
|
||||
defer cancel()
|
||||
resp, err := p.Chat(ctx, &agentAPI.CompletionRequest{
|
||||
Messages: []agentAPI.Message{msg},
|
||||
MaxTokens: maxTokens,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Sprintf("%s失败: %v", resultPrefix, err)
|
||||
}
|
||||
return fmt.Sprintf("[%s] %s", resultPrefix, resp.Content)
|
||||
}
|
||||
|
||||
func (a *Agent) executeDescribeImage(tc agentAPI.ToolCall) string {
|
||||
providerName, _ := tc.Arguments["provider"].(string)
|
||||
p := a.providerManager.Get(providerName)
|
||||
if p == nil {
|
||||
p = a.provider
|
||||
}
|
||||
detail, _ := tc.Arguments["detail"].(string)
|
||||
if detail == "" {
|
||||
detail = "high"
|
||||
}
|
||||
return a.mediaRequest(p, "image/png", "没有待处理的图片数据", "图片数据为空",
|
||||
a.inputCfg.Image.DescribePrompt, "图片描述", 2048, "image_url", detail)
|
||||
}
|
||||
|
||||
func (a *Agent) executeTranscribeAudio(tc agentAPI.ToolCall) string {
|
||||
providerName, _ := tc.Arguments["provider"].(string)
|
||||
p := a.providerManager.Get(providerName)
|
||||
if p == nil {
|
||||
p = a.provider
|
||||
}
|
||||
return a.mediaRequest(p, "audio/wav", "没有待处理的音频数据", "音频数据为空",
|
||||
a.inputCfg.Audio.DescribePrompt, "音频转写", 2048, "audio_url", "")
|
||||
}
|
||||
|
||||
func (a *Agent) executeOCRImage(tc agentAPI.ToolCall) string {
|
||||
return a.mediaRequest(a.provider, "image/png", "没有待处理的图片数据", "图片数据为空",
|
||||
a.inputCfg.Image.OCRPrompt, "OCR 结果", 4096, "image_url", "high")
|
||||
}
|
||||
138
internal/agent/core/multimodal_departed_test.go
Normal file
138
internal/agent/core/multimodal_departed_test.go
Normal file
@ -0,0 +1,138 @@
|
||||
// 结构性判据:多模态工具**已从内核退场**(2026-10-06)
|
||||
//
|
||||
// ## 为什么需要结构性判据
|
||||
//
|
||||
// 前面 plugin_test.go 验的是「插件侧行为对不对」。但这次改动的**要害**
|
||||
// 不是插件能不能用,而是**内核不再持有这三个工具** ——
|
||||
// 因为内核承诺零 IO,而它们要读本地文件。
|
||||
//
|
||||
// 行为判据抓不住这件事:哪怕把内核实现改回去,只要插件侧仍然工作,
|
||||
// 功能测试照样全绿。而「内核能不能读文件」正是本仓第一原则的红线。
|
||||
//
|
||||
// ⇒ 这条判据直接扫源码:三个工具名不得出现在 internal/agent/core/ 的
|
||||
//
|
||||
// 实现文件里,也不得有 os.ReadFile 之类为它们服务。
|
||||
package core
|
||||
|
||||
import (
|
||||
"os"
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// mediaToolNames 是已移出内核的三个工具。
|
||||
var mediaToolNames = []string{"describe_image", "ocr_image", "transcribe_audio"}
|
||||
|
||||
// kernelImplFiles 内核的实现文件(不含 _test.go —— 判据自身要断言的东西不该自己触发)。
|
||||
func kernelImplFiles(t *testing.T) []string {
|
||||
t.Helper()
|
||||
ents, err := os.ReadDir(".")
|
||||
if err != nil {
|
||||
t.Fatalf("读包目录: %v", err)
|
||||
}
|
||||
var out []string
|
||||
for _, e := range ents {
|
||||
n := e.Name()
|
||||
if strings.HasSuffix(n, "_test.go") || !strings.HasSuffix(n, ".go") {
|
||||
continue
|
||||
}
|
||||
out = append(out, n)
|
||||
}
|
||||
if len(out) < 5 {
|
||||
t.Fatalf("只找到 %d 个实现文件,判据覆盖不足", len(out))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// TestMediaToolsGoneFromKernel 钉住:内核实现里不再出现这三个工具名。
|
||||
//
|
||||
// ★ 这是本次改动的**核心不变量**。它对应 README 的第一原则:
|
||||
//
|
||||
// 内核零 IO,而这三个工具要读本地文件。
|
||||
func TestMediaToolsGoneFromKernel(t *testing.T) {
|
||||
for _, f := range kernelImplFiles(t) {
|
||||
b, err := os.ReadFile(f)
|
||||
if err != nil {
|
||||
t.Fatalf("读 %s: %v", f, err)
|
||||
}
|
||||
src := string(b)
|
||||
// 只看代码行:注释里可以说明「已移出」(那是给人看的)
|
||||
for _, line := range strings.Split(src, "\n") {
|
||||
trimmed := strings.TrimSpace(line)
|
||||
if strings.HasPrefix(trimmed, "//") {
|
||||
continue
|
||||
}
|
||||
for _, name := range mediaToolNames {
|
||||
if !strings.Contains(line, name) {
|
||||
continue
|
||||
}
|
||||
// 允许出现在「已移出」的说明性注释里(带 ★ 或 已移出 标记)
|
||||
if strings.Contains(line, "已移出") || strings.Contains(line, "★") {
|
||||
continue
|
||||
}
|
||||
t.Errorf("internal/agent/core/%s 仍出现 %q —— 它已移出为内置插件 multimodal:\n\t%s",
|
||||
f, name, trimmed)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestKernelHasNoMediaFileReading 钉住:内核不得为多模态读本地文件。
|
||||
//
|
||||
// ★ 比「名字没出现」更强:任何人新写一个 os.ReadFile 来干同样的事,
|
||||
//
|
||||
// 这条也会红。
|
||||
//
|
||||
// 已知例外:context.go 的上下文窗口持久化(savePath)属**记忆子系统**,
|
||||
// 已在允许清单里 —— 它不是多模态,且属于内核既有的职责。
|
||||
func TestKernelHasNoMediaFileReading(t *testing.T) {
|
||||
// 允许的内核磁盘读:上下文窗口持久化(记忆面)
|
||||
allowed := map[string]bool{
|
||||
"context.go": true, // RelevanceContext.savePath 的 load/save
|
||||
}
|
||||
readFile := regexp.MustCompile(`os\.(ReadFile|Open)\(`)
|
||||
for _, f := range kernelImplFiles(t) {
|
||||
if allowed[f] {
|
||||
continue
|
||||
}
|
||||
b, err := os.ReadFile(f)
|
||||
if err != nil {
|
||||
t.Fatalf("读 %s: %v", f, err)
|
||||
}
|
||||
for i, line := range strings.Split(string(b), "\n") {
|
||||
if readFile.MatchString(line) && !strings.HasPrefix(strings.TrimSpace(line), "//") {
|
||||
t.Errorf("internal/agent/core/%s:%d 出现磁盘读取 %q —— "+
|
||||
"内核承诺零 IO(多模态读文件已移到内置插件 multimodal)",
|
||||
f, i+1, strings.TrimSpace(line))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestMediaToolsRegisteredByPlugin 确认能力没丢:插件侧确实注册了这三个工具。
|
||||
//
|
||||
// ★ 与上一条成对:「内核不该有」+「插件要有」= 迁移而不是删除。
|
||||
//
|
||||
// 只断言前者会放过「直接删掉功能」这种退化。
|
||||
func TestMediaToolsRegisteredByPlugin(t *testing.T) {
|
||||
// 插件侧的注册清单在 internal/plugins/multimodal/plugin.go。
|
||||
// 这里只做**跨包引用检查**(core 包不该 import multimodal,那是反向依赖)。
|
||||
if strings.Contains(kernelSourceDump(t), `"gitcode.com/JianFeeeee/HomeAgent/internal/plugins/multimodal"`) {
|
||||
t.Error("core 反向 import 了 multimodal 插件 —— " +
|
||||
"工具由插件注册进 StageHost,核心不应知道插件实现")
|
||||
}
|
||||
}
|
||||
|
||||
func kernelSourceDump(t *testing.T) string {
|
||||
t.Helper()
|
||||
var sb strings.Builder
|
||||
for _, f := range kernelImplFiles(t) {
|
||||
b, err := os.ReadFile(f)
|
||||
if err != nil {
|
||||
t.Fatalf("读 %s: %v", f, err)
|
||||
}
|
||||
sb.Write(b)
|
||||
}
|
||||
return sb.String()
|
||||
}
|
||||
224
internal/agent/core/plugin_tools_service_test.go
Normal file
224
internal/agent/core/plugin_tools_service_test.go
Normal file
@ -0,0 +1,224 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
agentAPI "gitcode.com/JianFeeeee/HomeAgent/internal/agent/api"
|
||||
agentIO "gitcode.com/JianFeeeee/HomeAgent/internal/agent/io"
|
||||
)
|
||||
|
||||
// get_plugin_tools 必须是**完整**的服务(2026-05-05 修)
|
||||
//
|
||||
// ## ① 它数不到内置工具
|
||||
//
|
||||
// 原实现只收两处来源:
|
||||
//
|
||||
// StageHost.GetToolDefs() ← SDK 插件注册的
|
||||
// a.io.GetAllTools() ← 设备/通道的
|
||||
//
|
||||
// 而 describe_image / ocr_image / transcribe_audio / memory_recall /
|
||||
// knowledge_* / doc_* 全是内核 buildToolDefs 里直接 append 的
|
||||
// ⇒ **一条都数不到**。
|
||||
//
|
||||
// 症状:agent 能调这些工具,却调 get_plugin_tools("") 看不见它们。
|
||||
// 「工具不见了 / 怎么没有这个能力」时无处可查 —— 本项目反复踩的那类静默失效。
|
||||
//
|
||||
// ## ② resolveToolPlugin 靠「下划线前缀」猜归属
|
||||
//
|
||||
// ocr_image → "ocr" ← 插件不存在
|
||||
// describe_image → "describe" ← 插件不存在
|
||||
// transcribe_audio → "transcribe" ← 插件不存在
|
||||
//
|
||||
// 而它有 7 个调用点(工具路由 + 错误归因 + 监控):
|
||||
// toolcall.go:42 / task.go:710,892,939 / tooldefs.go:266 / 本文件两处。
|
||||
// 猜错 ⇒ 归属报给插件健康与监控,指向不存在的名字;
|
||||
// 且 `get_plugin_tools("ocr")` 会答「插件 ocr 没有可用的工具定义」。
|
||||
|
||||
// TestResolveToolPlugin_NoPhantomPlugins 钉住归属不得指向不存在的插件。
|
||||
func TestResolveToolPlugin_NoPhantomPlugins(t *testing.T) {
|
||||
a := newToolOwnerTestAgent(t)
|
||||
|
||||
// 这些内置工具的名字都含下划线,按旧规则会被截成假插件名。
|
||||
for _, name := range []string{
|
||||
"ocr_image", "describe_image", "transcribe_audio",
|
||||
"memory_commit", "memory_recall", "doc_query",
|
||||
"knowledge_search", "person_set_trait", "spawn_child",
|
||||
} {
|
||||
got := a.resolveToolPlugin(name)
|
||||
if got != "core" {
|
||||
t.Errorf("%s 归属为 %q,应为 core —— 旧规则会按下划线猜出"+
|
||||
"「%s」这个**不存在的插件**", name, got, strings.SplitN(name, "_", 2)[0])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestResolveToolPlugin_KnownPrefixStillResolves 确认没把真插件的归属也打死。
|
||||
//
|
||||
// 前缀规则对「确实是 <plugin>_<tool>」有意义(外部插件如 email_email_list)。
|
||||
// 判据是「该前缀是**已注册**插件」,而不是任何带下划线的名字。
|
||||
func TestResolveToolPlugin_KnownPrefixStillResolves(t *testing.T) {
|
||||
a := newToolOwnerTestAgent(t)
|
||||
// 无任何插件注册时,带下划线的名字一律归 core(不得编出插件名)
|
||||
if got := a.resolveToolPlugin("someplugin_someaction"); got != "core" {
|
||||
t.Errorf("未注册前缀应归 core,实际 %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestGetPluginTools_ListsBuiltinTools 钉住「内置工具必须能被列出」。
|
||||
//
|
||||
// ★ 断言要按**条件**写,不能假设某个工具一定在:
|
||||
//
|
||||
// ocr_image 受 core.input_processing.image.ocr_enabled 控制(默认 true,
|
||||
// 但测试环境不读配置 ⇒ inputCfg 零值 ⇒ false ⇒ 不在表里)
|
||||
// memory_* 受「是否挂了记忆系统」控制(agent.Memory == nil ⇒ 不在)
|
||||
//
|
||||
// 「无条件注册」指的是**不再被 pendingMedia 门挡住**,
|
||||
// 不是「无视一切配置开关」—— 那是两件事。
|
||||
func TestGetPluginTools_ListsBuiltinTools(t *testing.T) {
|
||||
a := newToolOwnerTestAgent(t)
|
||||
out := a.executeGetPluginTools("")
|
||||
if strings.Contains(out, "没有可用的工具定义") {
|
||||
t.Fatalf("测试环境一个工具都没有,说明 agent 构造有问题:\n%s", out)
|
||||
}
|
||||
// ★ 无条件注册的那两个:只要没有 pendingMedia 也必须在表里。
|
||||
// (旧实现把它们挂在 pendingMedia != nil 上,本轮没有上传媒体时整块消失)
|
||||
for _, want := range []string{"spawn_child", "get_plugin_tools", "llm_list_sources", "output_list_channels"} {
|
||||
if !strings.Contains(out, want) {
|
||||
t.Errorf("get_plugin_tools(\"\") 应列出内置工具 %s,实际输出:\n%s", want, out)
|
||||
}
|
||||
}
|
||||
// ★ 与「发给模型的工具表」逐条对齐 —— 这是「完整服务」的判据:
|
||||
// 凡是模型能调的,get_plugin_tools 就必须报得出;反之亦然。
|
||||
if missing := toolsMissingFromReport(t, a, out); missing != "" {
|
||||
t.Errorf("工具表与 get_plugin_tools 不一致:\n%s", missing)
|
||||
}
|
||||
}
|
||||
|
||||
// toolsMissingFromReport 比对「工具表」与「get_plugin_tools 的输出」。
|
||||
func toolsMissingFromReport(t *testing.T, a *Agent, report string) string {
|
||||
t.Helper()
|
||||
var missing []string
|
||||
for _, raw := range a.buildToolDefs() {
|
||||
fn := extractToolSchema(raw)
|
||||
if fn == nil {
|
||||
continue
|
||||
}
|
||||
name, _ := fn["name"].(string)
|
||||
if name == "" {
|
||||
continue
|
||||
}
|
||||
if !strings.Contains(report, "### "+name+"\n") {
|
||||
missing = append(missing, name)
|
||||
}
|
||||
}
|
||||
if len(missing) == 0 {
|
||||
return ""
|
||||
}
|
||||
return "模型能调但 get_plugin_tools 报不出:" + strings.Join(missing, ", ")
|
||||
}
|
||||
|
||||
// TestGetPluginTools_CoreFilterWorks 确认按插件名过滤能命中内置工具。
|
||||
func TestGetPluginTools_CoreFilterWorks(t *testing.T) {
|
||||
a := newToolOwnerTestAgent(t)
|
||||
out := a.executeGetPluginTools("core")
|
||||
if !strings.Contains(out, "spawn_child") {
|
||||
t.Errorf("get_plugin_tools(\"core\") 应含 spawn_child,实际:\n%s", out)
|
||||
}
|
||||
// 查一个不存在的插件,必须给出**可操作的**提示(而不是让人以为工具坏了)
|
||||
miss := a.executeGetPluginTools("ocr")
|
||||
if strings.Contains(miss, "describe_image") {
|
||||
t.Errorf("按不存在插件过滤时不该列出工具,实际:\n%s", miss)
|
||||
}
|
||||
if !strings.Contains(miss, "没有可用的工具定义") {
|
||||
t.Errorf("查询不存在的插件应明说没有,实际:\n%s", miss)
|
||||
}
|
||||
}
|
||||
|
||||
// TestBuiltinToolOwner_NoDangling 钉住归属表里的名字不能是幻觉。
|
||||
//
|
||||
// ★★ 这条判据我改过两次基准,两次都错,教训值得记:
|
||||
//
|
||||
// 第 1 版:拿运行时 buildToolDefs 当基准
|
||||
// ⇒ 错。memory_* / knowledge_* 受条件门控制(无 memory/knowledge 系统时
|
||||
// 不在表里),把「条件不满足」误报成「名字拼错了」。
|
||||
// 第 2 版:扫源码里的 toolDef("…") 字面量
|
||||
// ⇒ 也错。memory_recall 是由 internal/memory/indexer.go:442 **动态注入**的,
|
||||
// 源码里根本没有 toolDef("memory_recall" 这段文本。
|
||||
//
|
||||
// ⇒ 正确的基准是:**归属表的名字必须是内核真的会产出的工具名**。
|
||||
//
|
||||
// 判据改为「拼错的幻觉名」检测 —— 只断言一张**已知错名**清单里的名字
|
||||
// 不在表里。归属表多写一个不存在的名字,本判据立刻红;
|
||||
// 而条件门导致的「暂时不在表里」不会误报。
|
||||
func TestBuiltinToolOwner_NoDangling(t *testing.T) {
|
||||
// 一批**看起来像**内置工具、实际不存在的名字。
|
||||
// 写进归属表就是「幻觉归属」:agent 调它会被报成归属错误/找不到。
|
||||
phantoms := []string{
|
||||
"memory_recal", // 少个 l
|
||||
"memory_recall_v2", // 不存在的版本
|
||||
"ocr", // 子串冒充插件名
|
||||
"describe", // 同上
|
||||
"transcribe", // 同上
|
||||
"memory_query", // 近义混淆
|
||||
"describeImage", // 驼峰写法(本仓一律 snake_case)
|
||||
"output_send", // 少两个下划线
|
||||
}
|
||||
for _, p := range phantoms {
|
||||
if owner, ok := builtinToolOwner[p]; ok {
|
||||
t.Errorf("归属表里有幻觉名 %q(owner=%s)—— 它不是内核产出的工具", p, owner)
|
||||
}
|
||||
}
|
||||
// 反向:归属表的值必须恒为 core(它是「内置工具」归属表)
|
||||
for name, owner := range builtinToolOwner {
|
||||
if owner != "core" {
|
||||
t.Errorf("%q 的归属是 %q,但本表是**内置工具**归属表(应恒为 core)", name, owner)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestBuiltinToolOwner_CoversDeclaredTools 钉住「无条件声明的内置工具都登记了」。
|
||||
//
|
||||
// ★ 这条才是归属表的**核心**不变量:漏登记 ⇒ 退回「按下划线猜」
|
||||
//
|
||||
// ⇒ 又造出一个不存在的插件名(就是原缺陷)。
|
||||
// 基准取「无条件声明」的那批,因为它们在任何 agent 上都必然在工具表里。
|
||||
func TestBuiltinToolOwner_CoversDeclaredTools(t *testing.T) {
|
||||
a := newToolOwnerTestAgent(t)
|
||||
inTable := map[string]bool{}
|
||||
for _, raw := range a.buildToolDefs() {
|
||||
if fn := extractToolSchema(raw); fn != nil {
|
||||
if n, _ := fn["name"].(string); n != "" {
|
||||
inTable[n] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
// 测试环境里必然存在的内置工具,每一个都必须登记在归属表里。
|
||||
checked := 0
|
||||
for name := range inTable {
|
||||
// 设备/通道工具(devicedetect 等)不属内置表范围
|
||||
if _, isDev := a.io.DeviceOfTool(name); isDev {
|
||||
continue
|
||||
}
|
||||
if _, ok := builtinToolOwner[name]; !ok {
|
||||
t.Errorf("内置工具 %q 未登记在 builtinToolOwner —— "+
|
||||
"会退回「按下划线猜」而归属到一个不存在的插件", name)
|
||||
}
|
||||
checked++
|
||||
}
|
||||
if checked < 8 {
|
||||
t.Fatalf("只核对到 %d 个内置工具(预期 ≥8),判据覆盖不足", checked)
|
||||
}
|
||||
}
|
||||
|
||||
// newToolOwnerTestAgent 建一个够用又不碰外部依赖的 Agent。
|
||||
func newToolOwnerTestAgent(t *testing.T) *Agent {
|
||||
t.Helper()
|
||||
return New(AgentConfig{
|
||||
ID: "toolsvc",
|
||||
Provider: windowProvider{n: 200000},
|
||||
ProviderManager: agentAPI.NewProviderManager(),
|
||||
IO: agentIO.NewIOManager(),
|
||||
StageHost: NewStageHost(),
|
||||
})
|
||||
}
|
||||
@ -40,18 +40,98 @@ func (a *Agent) autoReloadPlugins() {
|
||||
}
|
||||
}
|
||||
|
||||
// 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{
|
||||
// 记忆子系统(内核能力,不是插件)
|
||||
"memory_recall": "core", "memory_commit": "core", "memory_merge": "core",
|
||||
"memory_purge": "core", "memory_edit": "core", "memory_delete_entity": "core",
|
||||
"memory_block_merge": "core", "memory_introspect": "core",
|
||||
"memory_document_query": "core", "memory_document_commit": "core",
|
||||
// 知识库
|
||||
"knowledge_search": "core", "knowledge_create": "core", "knowledge_list": "core",
|
||||
"knowledge_delete": "core", "knowledge_import_dir": "core",
|
||||
// 文档记忆
|
||||
"doc_query": "core", "doc_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",
|
||||
// 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",
|
||||
"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 {
|
||||
return name[:idx]
|
||||
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 {
|
||||
@ -84,9 +164,41 @@ func (a *Agent) executeGetPluginTools(pluginName string) string {
|
||||
items = append(items, toolItem{d.Name, d.Description, d.Parameters})
|
||||
}
|
||||
}
|
||||
// ★★ 收集**内置工具**(2026-05-05)。
|
||||
//
|
||||
// 原实<E58E9F><E5AE9E><EFBFBD>只收 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 没有可用的工具定义", pluginName)
|
||||
return fmt.Sprintf("插件 %s 没有可用的工具定义(它可能未加载/已禁用/已崩溃;用 get_plugin_tools(\"\") 看全量)", pluginName)
|
||||
}
|
||||
return "当前没有可用的工具定义"
|
||||
}
|
||||
@ -109,3 +221,18 @@ func (a *Agent) executeGetPluginTools(pluginName string) string {
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
@ -122,12 +122,11 @@ func (a *Agent) executeToolCallInner(tc agentAPI.ToolCall, channel string, turnS
|
||||
return toolOutcome{Text: a.executeChildResultTool(tc)}
|
||||
case strings.HasPrefix(tc.Name, "llm_"):
|
||||
return toolOutcome{Text: a.executeLLMTool(tc)}
|
||||
case tc.Name == "describe_image":
|
||||
return toolOutcome{Text: a.executeDescribeImage(tc)}
|
||||
case tc.Name == "transcribe_audio":
|
||||
return toolOutcome{Text: a.executeTranscribeAudio(tc)}
|
||||
case tc.Name == "ocr_image":
|
||||
return toolOutcome{Text: a.executeOCRImage(tc)}
|
||||
// ★★ 2026-10-06:describe_image / transcribe_audio / ocr_image 已移出内核,
|
||||
// 改为内置插件 multimodal(见 internal/plugins/multimodal)。
|
||||
// 理由:它们要读本地文件(IO),而内核承诺零 IO。
|
||||
// 这三个名字现在由 StageHost 路由到插件 —— 上面 if 走不到,
|
||||
// 会落到 stageHost.ExecuteTool,正是插件工具的正常路径。
|
||||
}
|
||||
|
||||
if a.stageHost != nil {
|
||||
|
||||
@ -646,33 +646,19 @@ func (a *Agent) buildToolDefs() []interface{} {
|
||||
},
|
||||
}, nil, parallelOpts()))
|
||||
|
||||
if a.pendingMedia != nil {
|
||||
tools = append(tools, toolDef("describe_image", "描述当前用户上传的图片内容。使用配置的多模态模型或默认 LLM 进行识别。调用此工具后你将获得图片的详细文字描述。", map[string]interface{}{
|
||||
"provider": map[string]interface{}{
|
||||
"type": "string",
|
||||
"description": "可选:用于图片描述的 LLM 源名称,不填则使用默认模型",
|
||||
},
|
||||
"detail": map[string]interface{}{
|
||||
"type": "string",
|
||||
"description": "描述详细程度: high / low / auto",
|
||||
"default": "high",
|
||||
},
|
||||
}))
|
||||
tools = append(tools, toolDef("transcribe_audio", "转写当前用户上传的音频内容为文字。使用配置的多模态模型或默认 LLM 进行语音识别。", map[string]interface{}{
|
||||
"provider": map[string]interface{}{
|
||||
"type": "string",
|
||||
"description": "可选:用于音频转写的 LLM 源名称,不填则使用默认模型",
|
||||
},
|
||||
}))
|
||||
if a.inputCfg.Image.OCREnabled {
|
||||
tools = append(tools, toolDef("ocr_image", "对当前用户上传的图片执行 OCR 文字识别,提取图片中的文字内容。适用于截图、文档照片、菜单等场景。", map[string]interface{}{
|
||||
"language": map[string]interface{}{
|
||||
"type": "string",
|
||||
"description": "OCR 语言(如 chi_sim+eng),默认自动",
|
||||
},
|
||||
}))
|
||||
}
|
||||
}
|
||||
// ★★ 2026-10-06:多模态工具已**移出内核**,改为内置插件 multimodal。
|
||||
//
|
||||
// 移出理由(README 第一原则):内核职责限定 LLM 编排/记忆/知识检索,
|
||||
// 而「读本地文件」是 IO —— 三个工具读文件却住在内核进程内,
|
||||
// 无沙箱、无能力面、无审计,正是 capability.go 那套权限梯度要防的事。
|
||||
//
|
||||
// 留在这里的是**待<><E5BE85>退场**的部分:下面这一大块 pendingMedia 只服务于
|
||||
// 那三个工具的工具面。input 通路(processInput 直接把 media block
|
||||
// 拼进本轮请求)**不依赖它**,所以可安全移除。
|
||||
// 退场顺序见 docs 或本次提交的说明;先确保插件侧能力等价。
|
||||
//
|
||||
// ⇒ describe_image / transcribe_audio / ocr_image 现在由插件注册,
|
||||
// 不再出现在这里。pendingMedia 的清理在本次一并处理。
|
||||
|
||||
return tools
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user