mirror of
https://gitcode.com/JianFeeeee/homeagent-sdk.git
synced 2026-10-31 06:17:25 +00:00
feat(examples): 内置插件外置化 —— cmd/localuse/mcp 迁入 example + files 新增按行号精确编辑
## 背景 主仓按「只有必须使用内部 SDK 能力的插件才内置」的判定标准(见主仓 ARCHITECTURE「内置插件的判定标准」)把纯公开 SDK 插件移出编译期内置清单。 本仓为它们提供外部插件工程(example/ 下,hmapdev 可直接构建)。 ★ 终审翻案:kbtree 与 multimodal **不**在本次外置之列 —— 逐方法对照 公开 SDK 后发现它们依赖内部专有能力(kbtree 要 KnowledgeAPI 的 Subtree/CategoryCounts/SearchIn/Categories 与树视图类型;multimodal 要 LLMAPI.Chat 与多模态消息类型),公开面没有,已加回主仓内置清单。 ## 新增工程(全部对齐当前模板 + 随用随起契约) | 工程 | 工具 | auto_start | 说明 | |---|---|---|---| | cmd | cmd_run | false(按需) | 沙箱执行 shell 命令 | | localuse | screensee/screensue/camerasue/speakeruse/clipboardsee/clipboardsue/computeruse | false(按需) | 本机外设 | | mcp | mcp_add/list/remove/restart_server | false(按需) | MCP 服务器接入(stdio/SSE) | 每工程:plg.json(含 sdk 字段声明)+ skill/<name>-tools/SKILL.md + README。按 auto_start 契约(sdk/autostart.go 的 OnDemandNeedsSkill), **auto_start=false 必须配 skill**,否则工具不出现在初始清单 ⇒ 模型不知道 它存在 ⇒ 永远不会被拉起,等于没装还占地方。 ## 移植要点 - 注册:内置版 init()+RegisterFactory → 外部版导出 NewPluginFactory; RegisterPluginMeta 的显示名进 plg.json/plugin.json。 - mcp:本地 rpcRequest/rpcResponse/rpcError 与 hmapdev 生成的 z_proc_gen.go 同名冲突(构建期生成物与本目录源码同包编译), 本地类型改名 mcpRPC*;internal/safeclose 内联为 safeCloseChan (外部插件不能引 internal 包,close-of-closed-channel 纪律随之带过来)。 - module 名:cmd 的 go.mod 用 homeagent-cmd(避免与标准库 cmd 混淆); name_en 对齐插件名,hmapdev 以 toSnake(name_en) 命名产物 (此前误写 Command/Local,产物成了 command_/local_)。 ## files:新增 files_edit_line(按行号精确编辑) files_edit 要求 old 文本全文件唯一,改「第三个 case 的 break」这类 非唯一文本时只能退化为整文件重写(有损)。files_edit_line 按行号 定位,op=replace/insert/delete,支持: - 多条 edit 从后往前应用(前面行号不漂移) - expect 安全闸:行内容与预期不符则整体拒绝(防行号过期改错位置) - CRLF/末尾换行保真 skill 同步补 edit_line 行。测试 5 条(含 expect 拒绝路径)。 ## 验证 hmapdev build 四工程全过:cmd/localuse/mcp/files 产物齐; go test files 全绿。
This commit is contained in:
100
example/files/editline_test.go
Normal file
100
example/files/editline_test.go
Normal file
@ -0,0 +1,100 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func newTestPlugin(t *testing.T) *Plugin {
|
||||
t.Helper()
|
||||
inst, err := NewPluginFactory("files", nil)
|
||||
if err != nil { t.Fatal(err) }
|
||||
return inst.(*Plugin)
|
||||
}
|
||||
|
||||
// 精确替换:old 在文件里出现多次时 files_edit 拒绝,edit_line 按行号可改。
|
||||
func TestEditLineReplacesNonUniqueLine(t *testing.T) {
|
||||
p := newTestPlugin(t)
|
||||
dir := t.TempDir()
|
||||
p.filesDir = dir
|
||||
file := filepath.Join(dir, "a.go")
|
||||
content := "return nil\nx := 1\nreturn nil\n"
|
||||
os.WriteFile(file, []byte(content), 0644)
|
||||
|
||||
res, err := p.handleEditLine(map[string]interface{}{
|
||||
"path": file,
|
||||
"edits": []interface{}{map[string]interface{}{
|
||||
"line": float64(3), "op": "replace", "text": "return err",
|
||||
}},
|
||||
})
|
||||
if err != nil { t.Fatal(err) }
|
||||
_ = res
|
||||
got, _ := os.ReadFile(file)
|
||||
want := "return nil\nx := 1\nreturn err\n"
|
||||
if string(got) != want {
|
||||
t.Fatalf("第3行应被替换。\nwant: %q\ngot: %q", want, string(got))
|
||||
}
|
||||
}
|
||||
|
||||
func TestEditLineExpectGuard(t *testing.T) {
|
||||
p := newTestPlugin(t)
|
||||
dir := t.TempDir()
|
||||
p.filesDir = dir
|
||||
file := filepath.Join(dir, "a.txt")
|
||||
os.WriteFile(file, []byte("alpha\nbeta\ngamma\n"), 0644)
|
||||
|
||||
// 本插件的约定:工具级错误经**返回值**(isError:true)回传而非 Go error,
|
||||
// 与 handleEdit 一致 —— 断言返回体而不是 err。
|
||||
res, _ := p.handleEditLine(map[string]interface{}{
|
||||
"path": file,
|
||||
"edits": []interface{}{map[string]interface{}{
|
||||
"line": float64(2), "op": "replace", "text": "BETA", "expect": "delta",
|
||||
}},
|
||||
})
|
||||
m, _ := res.(map[string]interface{})
|
||||
if m == nil || m["isError"] != true {
|
||||
t.Fatalf("expect 不匹配应返回 isError:true,实际: %v", res)
|
||||
}
|
||||
content, _ := m["content"].(string)
|
||||
if !strings.Contains(content, "expected") {
|
||||
t.Fatalf("错误内容应指出 expect 不匹配: %s", content)
|
||||
}
|
||||
got, _ := os.ReadFile(file)
|
||||
if string(got) != "alpha\nbeta\ngamma\n" { t.Fatal("失败时文件不得被改") }
|
||||
}
|
||||
|
||||
func TestEditLineInsertAndDelete(t *testing.T) {
|
||||
p := newTestPlugin(t)
|
||||
dir := t.TempDir()
|
||||
p.filesDir = dir
|
||||
file := filepath.Join(dir, "a.txt")
|
||||
os.WriteFile(file, []byte("one\ntwo\n"), 0644)
|
||||
|
||||
if _, err := p.handleEditLine(map[string]interface{}{
|
||||
"path": file,
|
||||
"edits": []interface{}{
|
||||
map[string]interface{}{"line": float64(2), "op": "insert", "text": "one-five\none-b"}, // 插在 two 前
|
||||
map[string]interface{}{"line": float64(1), "op": "delete"},
|
||||
},
|
||||
}); err != nil { t.Fatal(err) }
|
||||
got, _ := os.ReadFile(file)
|
||||
// 从后往前应用:先删 line1(one),再在 line2(原 two)前插两行
|
||||
want := "one-five\none-b\ntwo\n"
|
||||
if string(got) != want { t.Fatalf("want %q got %q", want, string(got)) }
|
||||
}
|
||||
|
||||
func TestEditLineAppendAtEnd(t *testing.T) {
|
||||
p := newTestPlugin(t)
|
||||
dir := t.TempDir()
|
||||
p.filesDir = dir
|
||||
file := filepath.Join(dir, "a.txt")
|
||||
os.WriteFile(file, []byte("a\nb\n"), 0644)
|
||||
if _, err := p.handleEditLine(map[string]interface{}{
|
||||
"path": file,
|
||||
"edits": []interface{}{map[string]interface{}{"line": float64(3), "op": "insert", "text": "c"}},
|
||||
}); err != nil { t.Fatal(err) }
|
||||
got, _ := os.ReadFile(file)
|
||||
if string(got) != "a\nb\nc\n" { t.Fatalf("want a\\nb\\nc\\n got %q", string(got)) }
|
||||
}
|
||||
@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "files",
|
||||
"name_zh": "文件系统",
|
||||
"name_en": "File System",
|
||||
"name_en": "files",
|
||||
"version": "1.0.0",
|
||||
"description": "文件系统操作工具集(读取/写入/编辑/列表),提供沙箱化文件访问,支持配置工作目录。",
|
||||
"author": "HomeAgent",
|
||||
@ -16,4 +16,4 @@
|
||||
"replaces": {},
|
||||
"source_dirs": [],
|
||||
"auto_start": false
|
||||
}
|
||||
}
|
||||
@ -124,6 +124,43 @@ func (p *Plugin) Start(s *sdk.PluginSDK) error {
|
||||
},
|
||||
}, p.handleEdit)
|
||||
|
||||
s.RegisterTool(tp+"edit_line", sdk.ToolDef{
|
||||
Name: tp + "edit_line",
|
||||
Description: fmt.Sprintf("Replace or insert by **line number** within the sandbox (%s). "+
|
||||
"Use this instead of %sedit when the target text is not unique (e.g. a blank line, "+
|
||||
"a closing brace, or a repeated statement) — %sedit requires the old text to appear exactly "+
|
||||
"once and will refuse otherwise. Line numbers are 1-indexed and refer to the file as it is "+
|
||||
"before this call; multiple edits are applied bottom-up so earlier line numbers stay valid.",
|
||||
p.filesDir, p.name+"_", p.name+"_"),
|
||||
Parameters: map[string]interface{}{
|
||||
"type": "object",
|
||||
"properties": map[string]interface{}{
|
||||
"path": map[string]interface{}{"type": "string", "description": "File path relative to sandbox or absolute"},
|
||||
"edits": map[string]interface{}{
|
||||
"type": "array",
|
||||
"description": "Line-targeted operations. Do not overlap ranges. Applied from the last line to the first.",
|
||||
"items": map[string]interface{}{
|
||||
"type": "object",
|
||||
"properties": map[string]interface{}{
|
||||
"line": map[string]interface{}{"type": "integer", "description": "Target line (1-indexed)"},
|
||||
"op": map[string]interface{}{
|
||||
"type": "string",
|
||||
"description": "replace (default): replace that line | insert: insert new text *before* that line | delete: remove that line",
|
||||
},
|
||||
"text": map[string]interface{}{"type": "string", "description": "New text (may contain \\n for multiple lines). Omit for delete."},
|
||||
"expect": map[string]interface{}{
|
||||
"type": "string",
|
||||
"description": "Optional safety check: the current line must equal this exactly (ignoring trailing \\r). Guards against acting on a stale line number.",
|
||||
},
|
||||
},
|
||||
"required": []string{"line"},
|
||||
},
|
||||
},
|
||||
},
|
||||
"required": []string{"path", "edits"},
|
||||
},
|
||||
}, p.handleEditLine)
|
||||
|
||||
s.RegisterTool(tp+"ls", sdk.ToolDef{
|
||||
Name: tp + "ls",
|
||||
Description: fmt.Sprintf("List directory contents within the sandbox (%s). Directories are marked with / suffix.", p.filesDir),
|
||||
@ -464,6 +501,190 @@ func (p *Plugin) handleEdit(args map[string]interface{}) (interface{}, error) {
|
||||
}, nil
|
||||
}
|
||||
|
||||
// handleEditLine implements the edit_line tool: line-number targeted edits.
|
||||
//
|
||||
// ## 为什么除了 edit 还要这个
|
||||
//
|
||||
// files_edit 的判据是「old 文本在文件里**恰好出现一次**」。这个约束在真实
|
||||
// 改代码时经常不成立:
|
||||
//
|
||||
// · 改一个 `}`、一个空行、`return nil` —— 全文件出现几十次,edit 直接拒绝;
|
||||
// · 改「第三个 case 分支里的 break」—— 文本与前两个字节相同,无法定位。
|
||||
//
|
||||
// 于是模型只能退化成 read 全文 + write 全文,而那是有损的:整段重写会
|
||||
// 顺带改动空白/换行/文件末尾,diff 里再也看不出「只改了这一行」。
|
||||
//
|
||||
// 本工具按**行号**定位,不依赖文本唯一性;`expect` 提供可选的安全闸
|
||||
// (行内容与预期不符就整体放弃,防止拿到过期行号后改错地方)。
|
||||
func (p *Plugin) handleEditLine(args map[string]interface{}) (interface{}, error) {
|
||||
path, _ := args["path"].(string)
|
||||
if path == "" {
|
||||
return errorResult("path is required"), nil
|
||||
}
|
||||
absPath, err := p.resolvePath(path)
|
||||
if err != nil {
|
||||
return errorResult(err.Error()), nil
|
||||
}
|
||||
|
||||
rawEdits, ok := args["edits"].([]interface{})
|
||||
if !ok || len(rawEdits) == 0 {
|
||||
return errorResult("edits must be a non-empty array"), nil
|
||||
}
|
||||
|
||||
data, err := os.ReadFile(absPath)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return errorResult("file not found: " + path), nil
|
||||
}
|
||||
return errorResult("read error: " + err.Error()), nil
|
||||
}
|
||||
original := string(data)
|
||||
|
||||
// 按行切分并保留行尾信息:是否有 \r\n、末尾是否带换行。
|
||||
// 这两点必须原样还原,否则「精确替换一行」会顺手改掉整个文件的换行风格。
|
||||
crlf := strings.Contains(original, "\r\n")
|
||||
endsWithNewline := strings.HasSuffix(original, "\n")
|
||||
lines := strings.Split(original, "\n")
|
||||
if endsWithNewline {
|
||||
lines = lines[:len(lines)-1]
|
||||
}
|
||||
// 每行去掉 \r(若原文件是 CRLF),edit 内部统一按无 \r 的文本处理。
|
||||
for i := range lines {
|
||||
lines[i] = strings.TrimSuffix(lines[i], "\r")
|
||||
}
|
||||
|
||||
type op struct {
|
||||
line int
|
||||
kind string
|
||||
text string
|
||||
expect string
|
||||
idx int
|
||||
}
|
||||
var ops []op
|
||||
var errors []string
|
||||
|
||||
for i, raw := range rawEdits {
|
||||
edit, ok := raw.(map[string]interface{})
|
||||
if !ok {
|
||||
errors = append(errors, fmt.Sprintf("edit[%d]: invalid format", i))
|
||||
continue
|
||||
}
|
||||
ln64, err := toInt64(edit["line"])
|
||||
if err != nil || ln64 < 1 {
|
||||
errors = append(errors, fmt.Sprintf("edit[%d]: line must be a positive integer", i))
|
||||
continue
|
||||
}
|
||||
kind, _ := edit["op"].(string)
|
||||
if kind == "" {
|
||||
kind = "replace"
|
||||
}
|
||||
if kind != "replace" && kind != "insert" && kind != "delete" {
|
||||
errors = append(errors, fmt.Sprintf("edit[%d]: op must be replace|insert|delete, got %q", i, kind))
|
||||
continue
|
||||
}
|
||||
text, _ := edit["text"].(string)
|
||||
if kind != "delete" && text == "" && edit["text"] == nil {
|
||||
errors = append(errors, fmt.Sprintf("edit[%d]: text is required for op=%s", i, kind))
|
||||
continue
|
||||
}
|
||||
expect, _ := edit["expect"].(string)
|
||||
ops = append(ops, op{line: int(ln64), kind: kind, text: text, expect: expect, idx: i})
|
||||
}
|
||||
|
||||
if len(errors) > 0 {
|
||||
return errorResult("invalid edits: " + strings.Join(errors, "; ")), nil
|
||||
}
|
||||
|
||||
// 行号允许等于 len(lines)+1 用于在文件末尾追加(insert)。
|
||||
for _, o := range ops {
|
||||
if o.line > len(lines)+1 {
|
||||
return errorResult(fmt.Sprintf(
|
||||
"edit[%d]: line %d is out of range (file has %d lines)", o.idx, o.line, len(lines))), nil
|
||||
}
|
||||
}
|
||||
|
||||
// ★ 从后往前应用:这样前面编辑的行号不受影响,调用方可以用「一次性
|
||||
// 基于原始文件的行号」来描述多处修改,无需自己算偏移。
|
||||
sort.SliceStable(ops, func(a, b int) bool { return ops[a].line > ops[b].line })
|
||||
|
||||
for _, o := range ops {
|
||||
pos := o.line - 1 // 0-indexed 插入/替换位置
|
||||
switch o.kind {
|
||||
case "insert":
|
||||
// 允许 line == len(lines)+1:追加到末尾。
|
||||
if pos > len(lines) {
|
||||
pos = len(lines)
|
||||
}
|
||||
newLines := strings.Split(o.text, "\n")
|
||||
lines = append(lines[:pos], append(newLines, lines[pos:]...)...)
|
||||
case "delete":
|
||||
if pos >= len(lines) {
|
||||
return errorResult(fmt.Sprintf(
|
||||
"edit[%d]: cannot delete line %d (file has %d lines)", o.idx, o.line, len(lines))), nil
|
||||
}
|
||||
if o.expect != "" && lines[pos] != o.expect {
|
||||
return errorResult(fmt.Sprintf(
|
||||
"edit[%d]: line %d is %q, expected %q — file changed since you read it; re-read and retry",
|
||||
o.idx, o.line, lines[pos], o.expect)), nil
|
||||
}
|
||||
lines = append(lines[:pos], lines[pos+1:]...)
|
||||
case "replace":
|
||||
if pos >= len(lines) {
|
||||
return errorResult(fmt.Sprintf(
|
||||
"edit[%d]: cannot replace line %d (file has %d lines); use op=insert to append",
|
||||
o.idx, o.line, len(lines))), nil
|
||||
}
|
||||
// expect 是安全闸:行号过期时宁可报错,也不要在错误位置写内容。
|
||||
if o.expect != "" && lines[pos] != o.expect {
|
||||
return errorResult(fmt.Sprintf(
|
||||
"edit[%d]: line %d is %q, expected %q — file changed since you read it; re-read and retry",
|
||||
o.idx, o.line, lines[pos], o.expect)), nil
|
||||
}
|
||||
newLines := strings.Split(o.text, "\n")
|
||||
lines = append(lines[:pos], append(newLines, lines[pos+1:]...)...)
|
||||
}
|
||||
}
|
||||
|
||||
sep := "\n"
|
||||
if crlf {
|
||||
sep = "\r\n"
|
||||
}
|
||||
out := strings.Join(lines, sep)
|
||||
if endsWithNewline {
|
||||
out += sep
|
||||
}
|
||||
|
||||
if err := os.WriteFile(absPath, []byte(out), 0644); err != nil {
|
||||
return errorResult("write error: " + err.Error()), nil
|
||||
}
|
||||
|
||||
return map[string]interface{}{
|
||||
"content": fmt.Sprintf("Successfully applied %d line edit(s) to %s (%d lines now)",
|
||||
len(ops), path, len(lines)),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// toInt64 宽容地把 JSON 数字(float64)或字符串转成 int64。
|
||||
func toInt64(v interface{}) (int64, error) {
|
||||
switch n := v.(type) {
|
||||
case float64:
|
||||
return int64(n), nil
|
||||
case int:
|
||||
return int64(n), nil
|
||||
case int64:
|
||||
return n, nil
|
||||
case json.Number:
|
||||
return n.Int64()
|
||||
case string:
|
||||
var i int64
|
||||
if _, err := fmt.Sscanf(n, "%d", &i); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return i, nil
|
||||
}
|
||||
return 0, fmt.Errorf("cannot convert %T to int64", v)
|
||||
}
|
||||
|
||||
// handleLs implements the ls tool.
|
||||
func (p *Plugin) handleLs(args map[string]interface{}) (interface{}, error) {
|
||||
path, _ := args["path"].(string)
|
||||
|
||||
@ -22,7 +22,8 @@ plugin_start name=files
|
||||
|---|---|
|
||||
| `files_read` | 读文件内容 |
|
||||
| `files_write` | 写文件(覆盖) |
|
||||
| `files_edit` | 局部替换编辑 |
|
||||
| `files_edit` | 局部替换编辑(old 文本须全文件唯一) |
|
||||
| `files_edit_line` | **按行号**精确替换/插入/删除(目标文本不唯一时用它,如改第 N 个 `}`) |
|
||||
| `files_ls` | 列目录 |
|
||||
|
||||
## 用完可释放
|
||||
|
||||
Reference in New Issue
Block a user